[英]How to Clear the window in tkinter (Python)?
我想使用“hide_widgets”功能隐藏/删除窗口中的所有按钮(临时),以便我可以将它们放回去,但它对我不起作用,我尝试使用grid_hide()
和destroy()
以及任何我已经尝试过搜索 stackoverflow 也没有奏效。
到目前为止,这是我的程序:
from tkinter import *
class Application(Frame):
#GUI Application
def __init__(self, master):
#Initialize the Frame
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
#Create new game etc...
#Title
self.title = Label(self,text = "Gnome")
self.title.grid()
#New Game
self.new_game = Button(self,text = "New Game")
self.new_game ["command"] = self.create_new_game
self.new_game.grid()
#Load Game
self.load_game = Button(self,text = "Load Game")
self.load_game ["command"] = self.display_saves
self.load_game.grid()
#Settings
self.settings = Button(self,text = "Settings")
self.settings ["command"] = self.display_settings
self.settings.grid()
#Story
self.story = Button(self,text = "Story")
self.story ["command"] = self.display_story
self.story.grid()
#Credits
self.credits = Button(self,text = "Credits")
self.credits ["command"] = self.display_credits
self.credits.grid()
def hide_widgets(self):
#clear window
new_game.grid_forget()
def create_new_game(self):
#Create new game file
self.hide_widgets
self.instruction = Label(self, text = "Name World:")
self.instruction.grid()
self.world_name = Entry(self)
self.world_name.grid()
def display_saves(self):
#display saved games and allow to run
print("saves")
def display_settings(self):
#display settings and allow to alter
print("settings")
def display_story(self):
#display story
print("story")
def display_credits(self):
#display credits
print("credits")
root = Tk()
root.title("Welcome")
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry('%dx%d+0+0' % (width,height))
app = Application(root)
root.mainloop()
提前谢谢你。
您可以通过调用每个人的grid_forget()
方法来隐藏Button
。
为了使这更容易,您可能需要创建一个包含所有self.buttons
列表或字典。
或者,您还可以在Application
实例上使用grid_slaves()
方法,该方法将为您提供它管理的所有小部件的列表(或仅指定行或列中的小部件)。 Button
应该在这些列表之一中。 我从未使用过它,所以我不知道在返回的列表中识别它们有多么容易。
你试过用new_game.grid_forget()
替换self.new_game.grid_forget()
吗?
查看此答案以解释为什么需要明确引用self
。 我运行了一个非常简单的脚本来测试这种行为,并且运行良好。
好的,我现在开始工作了,愚蠢的我忘记了self.hide_widgets()
“()”,我只是从没想过它,因为没有错误,因为它正在创建一个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.