[英]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.