你可以在开始创建空的标签,后来只更改文本在这个标签
import tkinter as tk
# --- functions ---
def f(s):
if s == "btn":
l['text'] = "one blah blah"
elif s == "btn2":
l['text'] = "two"
else:
print('ERROR: unknow:', s)
# --- main ---
root = tk.Tk()
root.geometry("100x100")
v = tk.StringVar(value="f")
a = tk.OptionMenu(root, v, "btn", "btn2", command=f)
a.grid(column=1, row=1)
l = tk.Label(root)
l.grid(column=1, row=2)
root.mainloop()
如果有删除Label
(因为你必须把不同的部件 - 即Button
),然后使用destroy()
import tkinter as tk
# --- functions ---
def f(s):
global w # inform function to use external variable when you will use `=`
if s == "label":
if w: # check if widget already exist
w.destroy()
w = tk.Label(root, text="Hello World!")
w.grid(column=1, row=2)
elif s == "button":
if w: # check if widget already exist
w.destroy()
w = tk.Button(root, text="Click Me")
w.grid(column=1, row=2)
else:
print('ERROR: unknow:', s)
# --- main ---
root = tk.Tk()
root.geometry("100x100")
v = tk.StringVar(value="f")
a = tk.OptionMenu(root, v, "label", "button", command=f)
a.grid(column=1, row=1)
w = None # create global variable without value
# to use later with widget (and keep access to this widget)
root.mainloop()
BTW:您可以创建小部件只有一次,更换他们 - 然后用grid_forget()
隐藏控件
import tkinter as tk
# --- functions ---
def f(s):
global w # inform function to use external variable when you will use `=`
if s == "label":
if w: # check if widget already exist
w.grid_forget()
w = l
w.grid(column=1, row=2)
elif s == "button":
if w: # check if widget already exist
w.grid_forget()
w = b
w.grid(column=1, row=2)
else:
print('ERROR: unknow:', s)
# --- main ---
root = tk.Tk()
root.geometry("100x100")
v = tk.StringVar(value="f")
a = tk.OptionMenu(root, v, "label", "button", command=f)
a.grid(column=1, row=1)
# create but not display
l = tk.Label(root, text="Hello World!")
b = tk.Button(root, text="Click Me")
w = None # create global variable without value
# to use later with widget (and keep access to this widget)
root.mainloop()
功能可短,如果你检查所有可能的值s
def f(s):
global w # inform function to use external variable when you will use `=`
if w: # check if widget already exist
w.grid_forget()
if s == "label":
w = l
elif s == "button":
w = b
w.grid(column=1, row=2)
不管你尝试可能给你一个错误信息。该错误消息告诉你到底是什么问题。告诉我们你已经尝试了什么,以及错误是什么。 –
开始创建空标签,然后您可以更改此标签中的文本 - 您不必删除标签。 – furas