【问题标题】:Why isn't my label configuring correctly? [duplicate]为什么我的标签配置不正确? [复制]
【发布时间】:2021-06-30 14:59:05
【问题描述】:

我希望在用户输入文本并点击 go 但标签未配置后将此标签配置到文本条目中。

我想要标有“你好!”的标签更改为放在主条目中的任何内容。我正在寻找用完整代码而不是固定行编写的答案。

这是我的代码:

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())
entry_frame = tk.Frame(root)
main_entry = tk.Entry(entry_frame, width=100)
main_entry.grid(row=0, column=0)
go_button = tk.Button(entry_frame, text= 'Go!', width=85, command= answer)
go_button.grid(row=1, column=0)
answer_label = tk.Label(text = "Hello!").pack()
entry_frame.place(relx=.5, rely=.5, anchor='center')


root.mainloop()

【问题讨论】:

  • answer_label = tk.Label(text = "Hello!").pack() -> answer_label = tk.Label(text = "Hello!") \n answer_label.pack() 在两个不同的行中
  • 另外,this 的回答已经有你的问题了。只有当你足够关注你才会得到答案。
  • @JacksonPro 他没有帮我解决我真正想要的问题,但在下面回答的人没有问题
  • 好吧,我的错,但解决方案确实存在于那个答案中。此外,您不需要按照以下答案的建议传递标签。只需将其写成两行就足够了。

标签: python python-3.x tkinter pycharm


【解决方案1】:

1.拆分tk.Labelpack()

2.通过标签。

  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):
        answer_label.config(text=main_entry.get())
    entry_frame = tk.Frame(root)
    main_entry = tk.Entry(entry_frame, width=100)
    main_entry.grid(row=0, column=0)
    answer_label = tk.Label(text = "Hello!")
    answer_label.pack()
    go_button = tk.Button(entry_frame, text= 'Go!', width=85, command=lambda: answer(answer_label))
    go_button.grid(row=1, column=0)
    entry_frame.place(relx=.5, rely=.5, anchor='center')
    
    root.mainloop()

【讨论】:

  • 如何根据用户所说的内容编写代码来配置标签,例如,如果用户说嘿并点击 go,我想让标签说“嘿(无论他当时放什么冒号):嗨!”。能否发一个“answer”功能下的示例代码?
  • 我不太确定您想要实现什么,但您可以查看您的answer 函数以了解任何输入/用例。def answer(answer_label): answer_label.config(text=f'{main_entry.get()}:Hi!')
猜你喜欢
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2011-12-16
  • 1970-01-01
  • 2013-02-09
  • 2017-05-30
相关资源
最近更新 更多