我希望我的“退出”按钮关闭窗口并结束程序,无论何时按下它。现在它首先按下它是有效的,但如果先按下“滚动”按钮,那么“退出”按钮不会关闭窗口。我是初学程序员,所以我确定我的代码存在无关的问题,但如果你能帮我解决这个问题,请提前感谢!
from Tkinter import *
from random import randint
class Application(Frame):
def displayBoard(self):
self.canvas1 = Canvas(self, width=200, height=200)
self.canvas1.pack()
self.canvas2 = Canvas(self, width=200, height=200)
self.canvas2.pack()
self.roll_button = Button(self, text="Roll the Dice", command=self.roll)
self.roll_button.pack()
self.clear = Button(self, text="Clear", command=self.resetBoard)
self.clear.pack()
self.quit = Button(self, text="Quit", command=self.quit)
self.quit.pack()
def __init__(self, master=None):
Frame.__init__(self, master)
Pack.config(self)
def roll(self):
die1 = faces[(randint(1,6)-1)]
die2 = faces[(randint(1,6)-1)]
self.resetBoard()
self.canvas1.create_text(20, 30, anchor=W, text=die1)
self.canvas1.pack()
self.canvas2.create_text(20, 30, anchor=W, text=die2)
self.canvas2.pack()
def resetBoard(self):
self.canvas1.destroy()
self.canvas2.destroy()
self.clear.destroy()
self.roll_button.destroy()
self.quit.destroy()
self.displayBoard()
def quit(self):
self.master.quit()
self.master.destroy()
master = Tk()
face1 = """\n
__________
| |
| |
| ( ) |
| |
|__________|
"""
face2 = """\n
__________
| |
| ( ) |
| |
| ( ) |
|__________|
"""
face3 = """ \n
__________
| |
| ( ) |
| ( ) |
| ( ) |
|__________|
"""
face4 = """\n
__________
| |
| ( ) ( ) |
| |
| ( ) ( ) |
|__________|
"""
face5 = """ \n
__________
| |
| ( ) ( ) |
| ( ) |
| ( ) ( ) |
|__________|
"""
face6 = """ \n
__________
| |
| ( ) ( ) |
| ( ) ( ) |
| ( ) ( ) |
|__________|
"""
faces = [face1, face2, face3, face4, face5, face6]
dicegame = Application()
dicegame.displayBoard()
dicegame.mainloop()
答案 0 :(得分:0)
(对于有这个问题的后来程序员在这里偶然发现)
问题在于您拥有功能 self.quit
而 按钮self.quit
。 Python不会重载名称 - 初始化后的self.quit
是一个函数,但是在您第一次调用self.resetBoard
之后,按钮与self.quit
相关联 - 销毁你对函数的引用。
解决方法是重命名其中一个,并记住避免命名冲突。一些pythonic方式包括:
self._quit()
self.quit_()
self.quit_button
;或者你的功能,即self.on_quit()
,self.quit_app()
,self.destroy()
(请注意,最后一个人需要调用super()。destroy(),否则你会破坏内容)