为什么当我使用 tkinter 配置选项时这个标签没有改变

问题描述

我想更改此标签,因此我使用了 widget.config 选项,但由于某种原因它不起作用。这是我的代码

import tkinter as tk

root = tk.Tk()
root.attributes('-fullscreen',True)


exit_button = tk.Button(root,text="Exit",command = root.destroy)
exit_button.place(x=1506,y=0)


def answer():
    global main_entry
    answer_label.config(main_entry)

frame = tk.Frame(root)
main_entry = tk.Entry(frame,width=100)
main_entry.grid(row=0,column=0)
go_button = tk.Button(frame,text='Go!',width=85,command = answer)
go_button.grid(row=1,column=0)
answer_label = tk.Label(text = "hey").pack()
frame.place(relx=.5,rely=.5,anchor='center')

root.mainloop()

解决方法

在使用 config 功能时,您必须提及要更改的内容。 尝试:- answer_label.config(text="Text that you want to be displayed")

此外,您还没有从 Entry 小部件中获取值:为此,您可以使用: answer_label.config(text=main_entry.get())

完整代码如下所示:

import tkinter as tk

root = tk.Tk()
root.attributes('-fullscreen',True)


exit_button = tk.Button(root,text="Exit",command = root.destroy)
exit_button.place(x=1506,y=0)


def answer():
    answer_label.config(text=main_entry.get())

frame = tk.Frame(root)
main_entry = tk.Entry(frame,width=100)
main_entry.grid(row=0,column=0)
go_button = tk.Button(frame,text='Go!',width=85,command = answer)
go_button.grid(row=1,column=0)
answer_label = tk.Label(text = "Hey")
answer_label.pack()
frame.place(relx=.5,rely=.5,anchor='center')

root.mainloop()
,

此代码有效。它配置标签以更改文本。我不知道你想通过 config(main_entry) 实现什么。

import tkinter as tk

root = tk.Tk()
root.attributes('-fullscreen',y=0)


def answer():
    global main_entry,answer_label
    answer_label.config(text="hi")

frame = tk.Frame(root)
main_entry = tk.Entry(frame,anchor='center')

root.mainloop()