我需要制作一个能够结束游戏的弹出窗口。弹出窗口可以在游戏类的内部或外部。目前,它只关闭一个画布,当用户点击"关闭"
时,如何让它自己关闭,画布和canvas2from tkinter import *
import tkinter as tk
class Game(object):
def __init__(self, master):
master.title("Game")
self._master = master
self._canvas2 = tk.Canvas(master, bg='grey', width=300, height=50)
self._canvas2.pack()
self._canvas = tk.Canvas(master, bg='grey', width=300, height=200)
self._canvas.pack()
#if conditions met, open popup:
self.popup()
def popup(self):
end = Toplevel()
end.title("End")
msg = Message(end, text="The game has ended")
msg.pack()
button = Button(end, text="Close", command=self._canvas.destroy)
button.pack()
def main():
root = tk.Tk()
app = Game(root)
root.mainloop()
if __name__ == '__main__':
main()
我尝试过的其他选项:
command=self.destroy
,command=self.exit()
,command=self.quit()
请注意,由于分配限制,游戏必须是对象。还为我提供了底部的初始化。弹出窗口不一定是顶层窗口(但它确实需要使用tkinter),这只是我试图实现的窗口。
答案 0 :(得分:0)
解决方案是创建自己的函数来从按钮调用:
...
button = Button(end, text="Close", command=self.close)
...
def close(self):
self._canvas.destroy()
self._canvas2.destroy()