I created code in order to display a 3x3 grid of buttons for a Tic-Tac-Toe program i'm developing. The grid worked before but when i tried to put the code into a class i just get a blank screen when i try to run the program. This is my code:
from tkinter import *
buttons = {".!frame.!button": 0,
".!frame.!button2": 1,
".!frame.!button3": 2,
".!frame.!button4": 3,
".!frame.!button5": 4,
".!frame.!button6": 5,
".!frame.!button7": 6,
".!frame.!button8": 7,
".!frame.!button9": 8,
}
class GameBoard:
def __init__(self, master):
self.field = Frame(master)
self.field.grid
self.b1 = Button(self.field, text="-")
self.b1.bind("<Button-1>", self.setfield)
self.b1.grid(row=0, column=0)
self.b2 = Button(self.field, text="-")
self.b2.bind("<Button-1>", self.setfield)
self.b2.grid(row=0, column=1)
self.b3 = Button(self.field, text="-")
self.b3.bind("<Button-1>", self.setfield)
self.b3.grid(row=0, column=2)
self.b4 = Button(self.field, text="-")
self.b4.bind("<Button-1>", self.setfield)
self.b4.grid(row=1, column=0)
self.b5 = Button(self.field, text="-")
self.b5.bind("<Button-1>", self.setfield)
self.b5.grid(row=1, column=1)
self.b6 = Button(self.field, text="-")
self.b6.bind("<Button-1>", self.setfield)
self.b6.grid(row=1, column=2)
self.b7 = Button(self.field, text="-")
self.b7.bind("<Button-1>", self.setfield)
self.b7.grid(row=2, column=0)
self.b8 = Button(self.field, text="-")
self.b8.bind("<Button-1>", self.setfield)
self.b8.grid(row=2, column=1)
self.b9 = Button(self.field, text="-")
self.b9.bind("<Button-1>", self.setfield)
self.b9.grid(row=2, column=2)
def setfield(self, event):
print(buttons[str(event.widget)])
root = Tk()
board = GameBoard(root)
root.mainloop()
Could someone help me find out why i just get an empty frame when i run the program?
Could someone help me find out why i just get an empty frame when i run the program?
It is because you aren't adding it to the window. Consider this code:
self.field.grid
It does absolutely nothing. For the window to appear you must call the function:
self.field.grid()
In my opinion a class should never call grid
or pack
or place
on itself. That should be the job of the caller. It's a good habit to get in because it promotes code reuse.
Personally I would remove that line and change a couple of the last lines to this:
board = GameBoard(root)
board.grid() # or board.pack(...)
You are making way too much work for yourself. You can pass arguments to the callback. For example:
self.b1 = Button(self.field, text="-", command=lambda: setfield(1))
With that, your callback will be called with the parameter 1
, and you won't need to do any sort of lookup.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.