在 Tkinter 中有什么方法可以让小部件不可见?
- 2025-01-15 08:45:00
- admin 原创
- 91
问题描述:
类似这样的操作会让小部件正常显示:
Label(self, text = 'hello', visible ='yes')
而像这样的事情会导致小部件根本不出现:
Label(self, text = 'hello', visible ='no')
解决方案 1:
pack_forget
您可能对小部件的和方法感兴趣grid_forget
。在下面的示例中,单击按钮时按钮会消失
from Tkinter import *
def hide_me(event):
event.widget.pack_forget()
root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', hide_me)
btn.pack()
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', hide_me)
btn2.pack()
root.mainloop()
解决方案 2:
正如另一个答案中所述,一种选择是使用pack_forget
或grid_forget
。另一种选择是使用lift
和lower
。这会更改小部件的堆叠顺序。最终效果是您可以将小部件隐藏在兄弟小部件(或兄弟小部件的后代)后面。当您希望它们可见时,您可以lift
使用它们,当您希望它们不可见时,您可以使用lower
它们。
优点(或缺点...)是它们仍然占用主控件中的空间。如果您“忘记”了某个控件,其他控件可能会重新调整其大小或方向,但如果您升高或降低它们,则不会。
这是一个简单的例子:
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.frame = tk.Frame(self)
self.frame.pack(side="top", fill="both", expand=True)
self.label = tk.Label(self, text="Hello, world")
button1 = tk.Button(self, text="Click to hide label",
command=self.hide_label)
button2 = tk.Button(self, text="Click to show label",
command=self.show_label)
self.label.pack(in_=self.frame)
button1.pack(in_=self.frame)
button2.pack(in_=self.frame)
def show_label(self, event=None):
self.label.lift(self.frame)
def hide_label(self, event=None):
self.label.lower(self.frame)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
解决方案 3:
我知道这已经晚了几年了,但这是截至 2013 年 10 月 27 日 Google 对“Tkinter 隐藏标签”的第 3 次回应...所以如果有人像我几周前一样正在构建一个简单的 GUI 并且只希望出现一些文本而不通过“降低”或“提升”方法将其交换为另一个小部件,我想提供一个我使用的解决方法(Python2.7,Windows):
from Tkinter import *
class Top(Toplevel):
def __init__(self, parent, title = "How to Cheat and Hide Text"):
Toplevel.__init__(self,parent)
parent.geometry("250x250+100+150")
if title:
self.title(title)
parent.withdraw()
self.parent = parent
self.result = None
dialog = Frame(self)
self.initial_focus = self.dialog(dialog)
dialog.pack()
def dialog(self,parent):
self.parent = parent
self.L1 = Label(parent,text = "Hello, World!",state = DISABLED, disabledforeground = parent.cget('bg'))
self.L1.pack()
self.B1 = Button(parent, text = "Are You Alive???", command = self.hello)
self.B1.pack()
def hello(self):
self.L1['state']="normal"
if __name__ == '__main__':
root=Tk()
ds = Top(root)
root.mainloop()
这里的想法是,您可以使用“.cget('bg')” http://effbot.org/tkinterbook/widget.htm将 DISABLED 文本的颜色设置为父级的背景 ('bg'),使其“不可见”。按钮回调将标签重置为默认前景色,文本再次可见。
缺点是,即使你无法阅读文本,你仍然必须为文本分配空间,而且至少在我的电脑上,文本与背景不能完美融合。也许通过一些调整,颜色可能会更好,对于紧凑的 GUI,空白空间分配对于简短的宣传来说不应该太麻烦。
有关我如何发现颜色信息,请参阅默认窗口颜色 Tkinter 和十六进制颜色代码。
解决方案 4:
我也非常迟到了,但我会在这里留下我的答案,给其他可能像我一样来到这里的人,寻找如何隐藏用.place()
功能放置在屏幕上的东西,而不是.pack()
两者都不隐藏.grid()
。
简而言之,您可以通过将宽度和高度设置为零来隐藏小部件,如下所示:
widget.place(anchor="nw", x=0, y=0, width=0, height=0)
提供一些背景信息,以便您了解我的需求以及我如何实现这一点。在我的程序中,我有一个窗口需要显示几个我组织成 2 个框架的内容,如下所示:
[WINDOW - app]
[FRAME 1 - hMainWndFrame]
[Buttons and other controls (widgets)]
[FRAME 2 - hJTensWndFrame]
[other Buttons and controls (widgets)]
一次只需要看到一帧,因此在应用程序初始化时,我有如下内容:
hMainWndFrame = Frame(app, bg="#aababd")
hMainWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)
...
hJTensWndFrame = Frame(app, bg="#aababd")
我使用.place()
而不是.pack()
或 是.grid()
因为我特别想在窗口上为每个小部件设置精确的坐标。因此,当我想隐藏主框架并显示另一个框架(以及所有其他控件)时,我所要做的就是.place()
在每个框架上再次调用该函数,但为要隐藏的框架指定零宽度和高度,为要显示的框架指定必要的宽度和高度,例如:
hMainWndFrame.place(anchor="nw", x=0, y=0, width=0, height=0)
hJTensWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)
现在这是真的,我只在Frame
s 上测试过这个,没有在其他小部件上测试过,但我猜它应该适用于所有东西。
解决方案 5:
要隐藏小部件,您可以使用函数 pack_forget();要再次显示它,您可以使用 pack() 函数并在单独的函数中实现它们。
from Tkinter import *
root = Tk()
label=Label(root,text="I was Hidden")
def labelactive():
label.pack()
def labeldeactive():
label.pack_forget()
Button(root,text="Show",command=labelactive).pack()
Button(root,text="Hide",command=labeldeactive).pack()
root.mainloop()
解决方案 6:
我没有使用网格或包。
我只为我的小部件使用了位置,因为它们的大小和位置是固定的。
我想在框架上实现隐藏/显示功能。
这是演示
from tkinter import *
window=Tk()
window.geometry("1366x768+1+1")
def toggle_graph_visibility():
graph_state_chosen=show_graph_checkbox_value.get()
if graph_state_chosen==0:
frame.place_forget()
else:
frame.place(x=1025,y=165)
score_pixel = PhotoImage(width=300, height=430)
show_graph_checkbox_value = IntVar(value=1)
frame=Frame(window,width=300,height=430)
graph_canvas = Canvas(frame, width = 300, height = 430,scrollregion=(0,0,300,300))
my_canvas=graph_canvas.create_image(20, 20, anchor=NW, image=score_pixel)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.config(command=graph_canvas.yview)
vbar.pack(side=RIGHT,fill=Y)
graph_canvas.config(yscrollcommand=vbar.set)
graph_canvas.pack(side=LEFT,expand=True,fill=BOTH)
frame.place(x=1025,y=165)
Checkbutton(window, text="show graph",variable=show_graph_checkbox_value,command=toggle_graph_visibility).place(x=900,y=165)
window.mainloop()
请注意,在上面的例子中,勾选“显示图表”后,会出现垂直滚动条。
取消选中复选框后,图表会消失。
我在该区域安装了一些条形图,但为了使示例简单,我没有显示出来。
从上面学到的最重要的事情是使用 frame.place_forget() 来隐藏内容,并使用 frame.place(x=x_pos,y=y_pos) 来显示内容。
解决方案 7:
对于像我一样讨厌 OOP 的人来说(这是基于 Bryan Oakley 的回答)
import tkinter as tk
def show_label():
label1.lift()
def hide_label():
label1.lower()
root = tk.Tk()
frame1 = tk.Frame(root)
frame1.pack()
label1 = tk.Label(root, text="Hello, world")
label1.pack(in_=frame1)
button1 = tk.Button(root, text="Click to hide label",command=hide_label)
button2 = tk.Button(root, text="Click to show label", command=show_label)
button1.pack(in_=frame1)
button2.pack(in_=frame1)
root.mainloop()
解决方案 8:
import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
lb.config(visible=visible)
visiblelabel(x, False) # Hide
visiblelabel(x, True) # Show
PSconfig
可以改变任意属性:
x.config(text='Hello') # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold')) # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white') # Background: red, Foreground: white
这是 等的绕过StringVar
方法IntVar
。
解决方案 9:
我也有使用 .place(x=?,y=?) 函数的解决方案
show:bool = true
joystickbtn1 = LabelFrame(root, text="Btn 1", padx=50, pady=50, width=50,height=25, bg='red')
if(show):
joystickbtn1.place(x=250,y=105)
else:
joystickbtn1.place(x=-500,y=-500)
#This is not the most efficient solution as it is still calculated and drawn just outside the frame which effectively hides it, but it works, is concise and easy to remember