我正在使用tkinter为一些Python脚本创建一个小GUI。对于此GUI,我需要一个名为Combobox
的{{1}},其中包含三个选项:
combo
(用户不想提交数据)"none"
(用户只想提交一个值)"constant"
(用户想要提交多个值)根据"adjustable"
中的选择,应该有不同数量的委托
出现。第一个选项应该不显示任何条目(并删除所有"剩余的"
entrys),第二个应该只显示一个条目,第三个应该显示
两个人。对我来说创建这些托管没有问题,但我不知道如何
让它们消失一旦创建它们,它们一直保持到GUI为止
闭合。
我试过这样的事情:
combo
但正如我之前所说,一旦创建了一个条目,它就不再消失了。一世
还尝试了import tkinter as tk
master = tk.Tk()
var1 = tk.StringVar()
var2 = tk.StringVar()
def submit():
if choice.get() == "none": # all entry boxes schould disappear
entry1.destroy()
entry2.destroy()
if choice.get() == "constant": # only 1 entry box schould be visible
entry1 = tk.Entry(master, textvariable = var1)
entry1.grid(column = 0, row = 1)
entry2.destroy()
if choice.get() == "adjustable": # all entry boxes should be visible
entry1 = tk.Entry(master, textvariable = var1)
entry1.grid(column = 0, row = 1)
entry2 = tk.Entry(master, textvariable = var1)
entry2.grid(column = 0, row = 2)
choice = tk.StringVar(value = "none")
combo = ttk.Combobox(master, textvariable = choice, state = "readonly")
combo["values"] = ("none", "constant", "adjustable")
combo.grid(column = 0, row = 0)
action = tk.Button(master, text = "confirm", command = submit)
action.grid(column=1, row=0)
master.mainloop()
entry.grid_forget()
{}} {}}
没有工作。
我还尝试在entry.destroy()
之外声明entry1
和entry1
,但后来我
一旦它们被摧毁,我们就不知道如何重新创造它们。
答案 0 :(得分:0)
感谢jasonharper的帮助,我在另一个脚本工作时找到了解决方案。代码看起来像这样:
import tkinter as tk
from tkinter import ttk
master = tk.Tk()
var1 = tk.StringVar()
var2 = tk.StringVar()
def submit():
if choice.get() == "none": # all entry boxes schould disappear
entry1.grid_remove()
entry2.grid_remove()
if choice.get() == "constant": # only 1 entry box schould be visible
entry1.grid(column = 0, row = 1)
entry2.grid_remove()
if choice.get() == "adjustable": # all entry boxes should be visible
entry1.grid(column = 0, row = 1)
entry2.grid(column = 0, row = 2)
choice = tk.StringVar(value = "none")
combo = ttk.Combobox(master, textvariable = choice, state = "readonly")
combo["values"] = ("none", "constant", "adjustable")
combo.grid(column = 0, row = 0)
entry1 = tk.Entry(master, textvariable = var1)
entry2 = tk.Entry(master, textvariable = var2)
action = tk.Button(master, text = "confirm", command = submit)
action.grid(column=1, row=0)
master.mainloop()
现在所有的托管都会在需要时被删除或创建。删除主题中的文本您只需添加entry.delete(0,"end")
。
我希望这也能帮助别人。