【问题标题】:Why am I getting ugly curly brackets around my text in the label widget? - Tkinter为什么我在标签小部件中的文本周围出现难看的大括号? - Tkinter
【发布时间】:2012-01-08 07:51:51
【问题描述】:

我的标签小部件中的文本周围出现了大括号。输出是{Total tries: 0} 而不是Total tries: 0

这是我的代码的简短版本:

class Cell:
    def check(self):
        mem.tries += 1
        mem.update_tries()

class Memory(Frame):
    def __init__(self, master):
        super(Memory, self).__init__(master)
        self.grid()
        self.create_widgets()
        self.tries = 0

    def create_widgets(self):
        self.label = Label(self)
        self.label["text"] = "Total tries: 0",
        self.label["font"] = ("Helvetica", 11, "italic")
        self.label.grid(row = 7, columnspan = 7, pady = 5)

    def update_tries(self):
        self.label["text"] = "Total tries: " + str(self.tries)

root = Tk()
root.title("Memory")
root.geometry("365x355")
mem = Memory(root)
root.mainloop()

【问题讨论】:

    标签: python tkinter curly-brackets


    【解决方案1】:

    我不知道为什么会这样;但是,当我使用 Tkinter 时,我总是使用 StringVar 或使用 config 方法进行文本更新。 Here's 包含一些示例的页面。

    使用StringVar 的示例:

    # in class Memory
    
    def create_widgets(self):
      self.labelText = StringVar()
      self.label = Label(self, textvariable = self.labelText)
      ... rest of method ...
    
    def update_tries(self):
      self.labelText.set("Total tries: " + str(self.tries))
    

    【讨论】:

    • 我无法让它工作...感谢您提供指向该页面的链接 :)
    • 我仍然得到了大括号。现在问题已经解决了。无论如何感谢您的帮助。
    【解决方案2】:
    self.label["text"] = "Total tries: 0",
    

    行尾有一个逗号。逗号将分配给self.label["text"] 的值从字符串更改为元组。去掉逗号,花括号就被去掉了。

    【讨论】:

    • 在哪里可以找到有关self.label["text"] 的文档?我只知道textvariable/StringVar 方式。
    • 我在《绝对初学者的Python编程-第三版》一书中了解了“self.label["text"]”
    【解决方案3】:

    我遇到了类似的问题,但这些解决方案都不适合我。对于将来遇到此问题的任何人,我会在包含"Health and Fitness" 之类的空格的文本上收到错误消息,该空格将打印为{Health and Fitness}

    对我来说,解决方案是实例化标签,例如:

    score = 25
    tk.Label(container, text=("Health and Fitness",score)).pack()
    

    而是像这个

    toPrint = "Health and Fitness" + str(score)
    tk.Label(container, text=toPrint).pack()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-04
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 2020-08-18
      • 2015-08-21
      相关资源
      最近更新 更多