Why am I getting ugly curly brackets around my text in the label widget? - Tkinter
Asked Answered
A

3

5

I'm getting curly brackets around the text in my label widget. The output is {Total tries: 0} instead of Total tries: 0.

Here is a short version of my code:

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()
Anderton answered 28/11, 2011 at 21:52 Comment(0)
G
9
self.label["text"] = "Total tries: 0",

There is a comma at the end of the line. The comma changes the value being assigned to self.label["text"] from a string to a tuple. Remove the comma, and the curly braces get removed.

Gayla answered 28/11, 2011 at 22:6 Comment(2)
Where can I find documentation on self.label["text"]? I've only known about the textvariable/StringVar way.Peloquin
I learnt about "self.label["text"]" in the book "Python programming for the absolute beginner - third edition"Anderton
P
0

I don't know why that happens; however, when I've used Tkinter, I've always done text updates either with a StringVar or using the config method. Here's a page with some examples.

Example using a 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))
Providing answered 28/11, 2011 at 22:1 Comment(2)
I couldn't get it to work... Thanks for the link to that page though :)Anderton
I still got the curly brackets. The problem is solved now. Thanks for your help anyway.Anderton
D
0

I had a similar problem but none of these solutions worked for me. For anyone in the future that struggles with this, I get an error on text that contains a space in such as "Health and Fitness" which would be printed as {Health and Fitness}.

For me, the solution was to not instantiate the labels such as:

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

But rather, like this:

toPrint = "Health and Fitness" + str(score)
tk.Label(container, text=toPrint).pack()
Dieldrin answered 11/3, 2021 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.