Da mir geraten wurde meine Programme in klassen zu packen hab ich das mal am Beispiel von Tic Tac Toe versucht Kritik am Code ist erwünscht und ich hoffe dass es hier besser ist mit der OOP.
Was ich noch anders machen sollte ist das tauschen der Grafiken , aber ich weiß nicht wie ich das Widget konfigurieren soll wenn ich dem Widget keinen Namen zugeteilt habe.
Was auch noch anders gemacht werden sollte ist dass Toplevel Window, dass ich benutze um anzuzeigen welcher Spieler im Moment an der Reihe ist. Wenn ich das ganze in der bind anweisung aber an ein Frame binde funktioniert das ganze nicht.
Danke schon mal im Voraus für Kritik.
Code: Alles auswählen
from tkinter import *
class Main(object):
meta = "-- Version 0.1 --\n Written by Josu\n Tic Tac Toe in Python 3.2 "
player = 1 # 1/2
liste = [[" "," "," "],[" "," "," "],[" "," "," "]]
root = Tk()
options = Toplevel(root)
icon_c = PhotoImage(file="icon_clean.gif")
icon_x = PhotoImage(file="icon_x.gif") # player 1
icon_o = PhotoImage(file="icon_o.gif") # player 2
player_1 = PhotoImage(file="player_1.gif")
player_2 = PhotoImage(file="player_2.gif")
def __init__(self):
pass
def new_game(self):
self.liste = [[" "," "," "],[" "," "," "],[" "," "," "]]
self.create_main_window()
def toggle(self):
if self.player == 1:
self.player = 2
Label(self.options, image= self.player_2, width = 124, height = 124).grid(row= 0, rowspan = 2, column=0)
Button(self.options, text="New Game", width= 30, bg = "red", command=self.new_game).grid(row=1, column=1)
print("setted to 2")
elif self.player == 2:
self.player = 1
Label(self.options, image= self.player_1, width = 124, height = 124).grid(row= 0, rowspan = 2, column=0)
Button(self.options, text="New Game", width= 30, bg = "blue", command=self.new_game).grid(row=1, column=1)
print("setted to 1")
def pressed(self, event):
grid_info = event.widget.grid_info()
x = grid_info["row"]
y = grid_info["column"]
print(x)
print(y)
if self.player == 1:
if self.liste[int(x)][int(y)] == " ":
print("s")
self.liste[int(x)][int(y)] = "X"
Label(self.root, image=self.icon_x, width=128, height=128).grid(row=x, column=y)
self.toggle()
elif self.player == 2:
if self.liste[int(x)][int(y)] == " ":
print("s")
self.liste[int(x)][int(y)] = "O"
Label(self.root, image=self.icon_o, width=128, height=128).grid(row=x, column=y)
self.toggle()
mainloop()
def create_main_window(self):
""" Erstellt das Hauptfenster UND das options fenster """
self.root.title("Spielfeld")
for x in range(0, 3):
for y in range(0, 3):
Label(self.root, image=self.icon_c, width=128, height=128).grid(row=x, column=y)
self.root.bind("<Button-1>", self.pressed)
self.options.title("options")
Label(self.options, image= self.player_1, width = 124, height = 124).grid(row= 0, rowspan = 2, column=0)
Label(self.options, text = self.meta).grid(row=0, column=1)
Button(self.options, text="New Game", width= 30, bg = "green", command=self.new_game).grid(row=1, column=1)
mainloop()
Main().create_main_window()