button in frames in python -
design of game need develop strategic tic tac toe(where in each block of tic tac toe find tic tac toe)....so here created 9 frames , each frame has 9 buttons... when click button in frame changes appear in 1 frame ie; in (0,2) know because last frame called..so need rectify problem...i tried did not in advance here's code
from tkinter import * root = tk() root.title("simple design") root.geometry("300x300") class design: count = 0 def __init__(self): self.duplicates = {} self.block = {} self.button = {} in range(3): j in range(3): self.duplicates[i, j] = "." self.frame() def frame(self): i, j in self.duplicates: self.block[i, j] = frame(root, background="blue") self.block[i, j].grid(row=i, column=j, ipadx=5, ipady=2) self.button_create(self.block[i, j]) def button_create(self, frame): i, j in self.duplicates: handler = lambda a=i, b=j: self.update(a, b) self.button[i, j] = button(frame, command=handler, text=".", height=3, width=5) self.button[i, j].grid(row=i, column=j) def update(self, i, j): if (design.count % 2 == 0): self.button[i, j]["text"] = "x" design.count += 1 else: self.button[i, j]["text"] = "o" design.count += 1 self.button[i, j]["state"] = "disabled" print (i, j) d = design() # out of class root.mainloop()
there problem button handler: how can each button know coordinates?
just replace:
handler = lambda a=i, b=j: self.update(a, b)
by:
handler = lambda: self.update(i, j)
there bug in frame
method: iterate duplicates
, call button_create
again iterates duplicates
. buttons redefined in inner loop.
you can change button_create
this:
def button_create(self, frame, i, j): handler = lambda: self.update(i, j) self.button[i, j] = button(frame, command=handler, text=".", height=3, width=5) self.button[i, j].grid(row=i, column=j)
and adapt call in frame
follow:
def frame(self): i, j in self.duplicates: self.block[i, j] = frame(root, background="blue") self.block[i, j].grid(row=i, column=j, ipadx=5, ipady=2) self.button_create(self.block[i, j], i, j)
also note ought inherit object
class use new-style classes:
class design(object): ...
instead of if ... else
, can use mapping calculate symbol "x" or "o" in update
:
def update(self, i, j): symbol = {0: "x", 1: "o"}[design.count % 2] self.button[i, j]["text"] = symbol design.count += 1 self.button[i, j]["state"] = "disabled" print (i, j)
or simply:
symbol = "xo"[design.count % 2]
Comments
Post a Comment