1 回答
TA贡献1865条经验 获得超7个赞
下面是一个简单的示例,说明如何直接更新根窗口和全局命名空间中的任何变量。它只是您在从按钮调用的函数中执行的操作的问题。
如果您有任何疑问,请告诉我。
import tkinter as tk
root = tk.Tk()
root.config(background='white')
root.geometry('250x100')
label_1 = tk.Label(root, text=0)
label_1.pack()
label_2 = tk.Label(root, text='test')
label_2.pack()
def toggle_root_bg():
# check the color of the root window and toggle accordingly.
if root['background'] == 'black':
root.config(background='white')
else:
root.config(background='black')
def update_root_labels(one, two):
# Apply argument values to the text fields of the labels defined in the global namespace.
label_1.config(text=one)
label_2.config(text=two)
def sub_window():
# setting sub window variable name to be used with other widgets.
top = tk.Toplevel(root)
tk.Label(top, text='Provide a number: ').grid(row=0, column=0)
tk.Label(top, text='Provide a string: ').grid(row=1, column=0)
entry_1 = tk.Entry(top)
entry_2 = tk.Entry(top)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
# create a sub function to get the current entry field values
# then pass these values on to our update function.
def submit_update():
update_root_labels(entry_1.get(), entry_2.get())
tk.Button(top, text='Update root labels', command=submit_update).grid(row=2, column=0)
tk.Button(top, text='Toggle Root Background', command=toggle_root_bg).grid(row=3, column=0)
tk.Button(root, text='Open sub window', command=sub_window).pack()
root.mainloop()
以前:
后:
添加回答
举报