Skip to content
Advertisement

Tkinter Window: TypeError: can only concatenate str (not “int”) to str

I’m having trouble solving the Concatenate Error when it’s present in a Tkinter Window. I tried using multiple methods but, they didn’t work to well with what I’m trying to do. I’m trying to make it so where, at the click of a Tkinter button, it would randomly choose a value between 0 and 100. If the random value is less than or equal to 70, both “Good Guy” and “Bad Guy” would have their health reduced. But if it’s greater than 70, Good guy would only take damage. It would then print their new hp into the window.

from random import randrange


class App5(tk.Toplevel):
    def __init__(self, title: str):
        super().__init__()
        self.title(title)

        self.style = ttk.Style(self)
        self.style.theme_use("classic")
        self.geometry("490x250")

        self.tres_label = ttk.Label(
            self,
            text="Oh yeah, also while you were doing that, I enrolled you into a tournament. nHave fun........what? Why did I sign you up for a tournament you didn't ask for? nTo increase the total run time on this project.",
        )
        self.tres_label.grid(row=0, column=0, padx=5, pady=5)

        self.rng_button = ttk.Button(self, text="Click Me", command=self.rng)
        self.rng_button.grid(row=2, column=0, padx=5, pady=5)

    def rng(self):
        class Character:
            def __init__(self, name: str, hp: int, damage: int):
                self.name = name
                self.hp = hp
                self.damage = damage

        Goodguy = Character("Goodguy", 300, 75)
        Badguy = Character("Badguy", 375, 25)
        score = 70
        num = randrange(0, 100)
        G = Goodguy.hp - Badguy.damage
        B = Badguy.hp - Goodguy.damage

        if num >= score:
            Goodguy.hp - Badguy.damage
            Badguy.hp - Goodguy.damage
            self.good = ttk.Label(self, text="Goodguy Hp:" + G)
            self.good.grid(row=3, column=3)
            self.bad = ttk.Label(self, text="BadGuy Hp:" + B)
            self.bad.grid(row=3, column=6)
            B = B - Goodguy.damage
            G = G - Badguy.damage
        else:
            Goodguy.hp - Badguy.damage
            self.good = ttk.Label(self, text="Goodguy Hp:" + G)
            self.good.grid(row=3, column=3)
            self.bad = ttk.Label(self, text="BadGuy Hp:" + B)
            self.bad.grid(row=3, column=6)
            B = B - Goodguy.damage
            G = G - Badguy.damage

Advertisement

Answer

i suspect the issue is here:

self.good = ttk.Label(self, text="Goodguy Hp:" + G)

what type is G? if it’s an int you cannot add them together like you’re trying to do, you need to change it to text="Goodguy Hp: " + str(G), or use an f-string like @AKX mentioned

try changing this expression in all four places

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement