[英]Clearing specific widgets in tkinter
I am attempting to have a function in python that clears the screen upon a button being pressed. 我试图在python中有一个函数,当按下一个按钮时会清除屏幕。 I am aware of grid_remove but am unsure of how to use it.
我知道grid_remove,但是不确定如何使用它。 Also is there a way to clear everything from a specific function, ie both "hi" and "clear"?
还有没有办法清除特定功能(即“ hi”和“ clear”)中的所有内容?
from tkinter import *
class Movies:
def __init__(self, master):
hi = Label(text = "Hello")
hi.grid(row = 0, column = 0)
clear = Button(text = "Click", command=self.clear)
clear.grid(row = 1, column = 0)
def clear(self):
hi.grid_remove()
root = Tk()
gui = Movies(root)
root.geometry("100x200+0+0")
root.mainloop()
You could use the built in winfo_children
method if you're just wanting to toggle hiding / showing all of the widgets in whatever parent holds the widgets. 如果您只想切换隐藏/显示所有父控件中的所有控件,则可以使用内置的
winfo_children
方法。 Small example: 小例子:
from tkinter import *
class Movies:
def __init__(self, master):
self.master = master
self.state = 1
for i in range(5):
Label(self.master, text='Label %d' % i).grid(row=0, column=i)
self.magic_btn = Button(self.master, text='Make the Magic!',
command=self.magic)
self.magic_btn.grid(columnspan=5)
def magic(self):
self.state = not self.state
for widget in self.master.winfo_children(): #iterate over all child widgets in the parent
#Comment out to clear the button too, or leave to toggle widget states
if widget != self.magic_btn: #or some other widget you want to stay shown
if self.state:
widget.grid()
else:
widget.grid_remove()
print(self.state)
root = Tk()
gui = Movies(root)
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.