【问题标题】:Why isn't this label changing when I use the tkinter config option为什么当我使用 tkinter 配置选项时这个标签没有改变
【发布时间】:2021-06-29 08:14:55
【问题描述】:

我想更改此标签,因此我使用了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()

【问题讨论】:

    标签: python user-interface tkinter pycharm widget


    【解决方案1】:

    在使用配置功能时,您必须提及要更改的内容。 尝试:- 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()
    

    【讨论】:

    • 您没有错,您可以消除答案中的不确定性。还要记下将global 删除,因为它在那里没用。
    • 感谢您为我指明了正确的方向。
    • 你能告诉我这在我的完整代码中是什么样子吗?
    • 立即查看。我已经更新了解决方案。
    【解决方案2】:

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

    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
        answer_label.config(text="hi")
    
    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()
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      相关资源
      最近更新 更多