Python 在 Tkinter 中有什么方法可以使小部件不可见吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3819354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:53:27  来源:igfitidea点击:

In Tkinter is there any way to make a widget not visible?

pythontkinter

提问by rectangletangle

Something like this, would make the widget appear normally:

像这样的东西会使小部件正常显示:

Label(self, text = 'hello', visible ='yes') 

While something like this, would make the widget not appear at all:

虽然像这样,会使小部件根本不出现:

Label(self, text = 'hello', visible ='no') 

采纳答案by luc

You may be interested by the pack_forgetand grid_forgetmethods of a widget. In the following example, the button disappear when clicked

您可能对 小部件的pack_forgetgrid_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()

回答by Bryan Oakley

One option, as explained in another answer, is to use pack_forgetor grid_forget. Another option is to use liftand lower. This changes the stacking order of widgets. The net effect is that you can hide widgets behind sibling widgets (or descendants of siblings). When you want them to be visible you liftthem, and when you want them to be invisible you lowerthem.

如另一个答案中所述,一种选择是使用pack_forgetgrid_forget。另一种选择是使用liftlower。这会更改小部件的堆叠顺序。最终效果是您可以将小部件隐藏在同级部件(或同级部件的后代)后面。当您希望它们可见时,您就是lift它们,而当您希望它们不可见时,它们就是您lower

The advantage (or disadvantage...) is that they still take up space in their master. If you "forget" a widget, the other widgets might readjust their size or orientation, but if you raise or lower them they will not.

优点(或缺点......)是它们仍然占用它们主人的空间。如果您“忘记”了一个小部件,其他小部件可能会重新调整它们的大小或方向,但如果您升高或降低它们,它们就不会。

Here is a simple example:

这是一个简单的例子:

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()

回答by WellThatBrokeIt

I know this is a couple of years late, but this is the 3rd Google response now for "Tkinter hide Label" as of 10/27/13... So if anyone like myself a few weeks ago is building a simple GUI and just wants some text to appear without swapping it out for another widget via "lower" or "lift" methods, I'd like to offer a workaround I use (Python2.7,Windows):

我知道这已经晚了几年,但这是截至 2013 年 10 月 27 日 Google 对“Tkinter hide Label”的第 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()

The idea here is that you can set the color of the DISABLED text to the background ('bg') of the parent using ".cget('bg')" http://effbot.org/tkinterbook/widget.htmrendering it "invisible". The button callback resets the Label to the default foreground color and the text is once again visible.

这里的想法是,您可以使用“.cget('bg')” http://effbot.org/tkinterbook/widget.htm将禁用文本的颜色设置为父级的背景 ('bg')渲染它“无形的”。按钮回调将标签重置为默认前景色,文本再次可见。

Downsides here are that you still have to allocate the space for the text even though you can't read it, and at least on my computer, the text doesn't perfectly blend to the background. Maybe with some tweaking the color thing could be better and for compact GUIs, blank space allocation shouldn't be too much of a hassle for a short blurb.

这里的缺点是,即使您无法阅读文本,您仍然必须为文本分配空间,至少在我的计算机上,文本不能完美地融入背景。也许稍微调整一下颜色会更好,对于紧凑的 GUI,空白空间分配对于简短的介绍应该不会太麻烦。

See Default window colour Tkinter and hex colour codesfor the info about how I found out about the color stuff.

有关我如何发现颜色内容的信息,请参阅默认窗口颜色 Tkinter 和十六进制颜色代码

回答by bemygon

For someone who hate OOP like me (This is based on Bryan Oakley's answer)

对于像我这样讨厌 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()

回答by Saheb Singh

For hiding a widget you can use function pack_forget() and to again show it you can use pack() function and implement them both in separate functions.

要隐藏小部件,您可以使用函数 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()

回答by wyz23x2

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

P.S. configcan change any attribute:

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

It's a bypass of StringVar, IntVaretc.

这是一个旁路StringVarIntVar等等。