我创建了代码,以便为我正在开发的井字游戏程序显示一个 3x3 的按钮网格。网格以前工作过,但是当我尝试将代码放入一个类中时,当我尝试运行该程序时,我只会得到一个空白屏幕。这是我的代码:
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()
有人能帮我找出为什么我在运行程序时得到一个空帧吗?
SMILET
相关分类