【问题标题】:How to set a string to the text of a label in Tkinter?如何在 Tkinter 中将字符串设置为标签的文本?
【发布时间】:2021-01-01 13:56:38
【问题描述】:

我试图在 tkinter 程序中将字符串设置为标签的文本,但它在窗口中不可见。请帮我。一段代码在这里:

str=input()   
lbl=Label(win,text=str)
lbl.grid(row=11, column=1, ipadx=20, ipady=10, sticky=W + S)

【问题讨论】:

  • 除非你没有指定 win,否则它工作得很好。另外,避免使用 python 内置类作为变量名。
  • 你用过win.mainloop()吗?
  • 是的,我也在使用 win.mainloop()。窗口出现,但标签没有出现。
  • 最好避免在 GUI 应用程序中使用input()。请改用Entry 小部件。

标签: python tkinter label


【解决方案1】:

str 是 Python 中的关键字。尝试将其重命名为str1

from tkinter import *
str1=input()
root = Tk()
lbl=Label(text=str1)
lbl.grid(row=11, column=1, ipadx=20, ipady=10, sticky=W + S)
root.mainloop()

这就是我得到的

【讨论】:

  • 我用 str1 代替了 str 但它仍然没有出现。另外请告诉我如何从文件中读取字符串并将其设置为标签文本。
【解决方案2】:

这段代码可能会起作用,

from tkinter import *

class Application:
    def __init__(self):
        self.my_string = ""

        self.root = Tk()
        self.root.geometry("300x200+50+50")
        self.entry = Entry(self.root)
        self.entry.bind("<Return>", self.onReturn)
        self.entry.pack()

        self.my_label = Label(self.root, text="Initial text!")
        self.my_label.pack()

        self.root.mainloop()

    def onReturn(self, event):
        self.my_label.config(text=self.entry.get())
        self.entry.delete(0, END)

    Application()   

【讨论】:

  • 您能解释一下它是如何以及为什么起作用的吗?解决方案的关键部分是什么?
  • 为什么不直接使用text=my_string
猜你喜欢
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多