如何在Tkinter中显示/隐藏小部件?

2024-04-29 17:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个程序,在给定一系列用户输入的情况下执行一个函数。只有在某些情况下才需要几个用户输入,如果可能的话,我只想在选中一个复选按钮时显示这些输入值的输入框和标签,指示需要这些输入的情况存在。我不知道该怎么办:

  • 把我添加的标签和输入框放在已经存在的行之间。

  • 取消选中复选按钮时“隐藏”标签和输入框,而不destroy这些标签和输入框,以便在重新选中复选按钮时可以再次显示它们,而不会丢失任何已输入的数据。

    • 示例:我选择复选按钮,在出现的新框中输入数据,然后取消选择复选按钮(导致框不再显示)。如果我重新选择Checkbutton,那么上次选择Checkbutton时输入的数据应该仍然存在。
  • “显示”以前被“隐藏”的相同标签和输入框(如果在以前被取消选择后重新选择了复选按钮)。

我不知道这样的事情是否可能,但如果不可能,请告诉我。另外,我知道我可以简单地在取消选中复选按钮的同时将相关的输入框state设置为DISABLED,但是如果可能的话,我更希望这些框不会出现,这样它们的出现就不会混淆那些不熟悉需要额外输入的情况的用户。

如果这是相关的,我使用Python2.7.9、Anaconda2.2.0(64位)和Tkinter版本81008在Windows10Pro上。如果我遗漏了一些有用的信息,请随时索取进一步的信息。提前感谢你能提供的帮助。


Tags: 数据函数用户程序信息示例情况标签
1条回答
网友
1楼 · 发布于 2024-04-29 17:09:44

我想你想要grid_remove()

来自http://www.tkdocs.com/tutorial/grid.html

The "forget" method of grid, taking as arguments a list of one or more slave widgets, can be used to remove slaves from the grid they're currently part of. This does not destroy the widget altogether, but takes it off the screen, as if it had not been gridded in the first place. You can grid it again later, though any grid options you'd originally assigned will have been lost.

The "remove" method of grid works the same, except that the grid options will be remembered.

下面是一个丑陋的例子。播放网格选项和条目文本以查看它们是如何保留的。

def toggle_entry():
    global hidden
    if hidden:
        e.grid()
    else:
        e.grid_remove()
    hidden = not hidden

hidden = False
root = tk.Tk()
e = tk.Entry(root)
e.grid(row=0, column=1)
tk.Button(root, text='Toggle entry', command=toggle_entry).grid(row=0, column=0)
root.mainloop()

相关问题 更多 >