【发布时间】:2019-04-23 13:58:29
【问题描述】:
我创建了代码,以便为我正在开发的井字游戏程序显示一个 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()
有人可以帮我找出为什么我在运行程序时只是得到一个空框架吗?
【问题讨论】:
-
self.field.grid没有在末尾添加()什么都不做... -
好尴尬哈哈哈
-
你想用
buttons做什么?不能保证您输入的字符串是按钮的内部名称。这绝对不是 python 2.x 中的名字。 -
@BryanOakley 我希望每个按钮根据其在网格中的位置返回一个值,而不是为每个按钮创建单独的方法,因为我不知道如何将参数传递给 setfield 方法。我认为不能保证它会根据版本等保持不变,但这是我唯一能想到的(无论如何现在)
标签: python class user-interface tkinter