當 Tkinter 視窗中出現連接錯誤時,我無法解決它。我嘗試使用多種方法,但是它們對我正在嘗試做的事情并不奏效。我正在努力做到這一點,點擊 Tkinter 按鈕,它會隨機選擇 0 到 100 之間的值。如果隨機值小于或等于 70,則“好人”和“壞人” “會降低他們的健康水平。但如果大于 70,Good guy 只會受到傷害。然后它將他們的新馬力列印到視窗中。
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
uj5u.com熱心網友回復:
只能將 str(不是“int”)連接到 str
正在告訴您確切的錯誤是什么(并且無論如何您都應該將其添加到原始問題中的回溯會準確指出錯誤的位置)。
問題是你不能“總結”一個字串和一個整數。相反,使用字串格式:
"Goodguy Hp:" G
會成為
f"Goodguy Hp:{G}"
使用f 字串格式。
這同樣代表著其他好人和壞人的標簽。
uj5u.com熱心網友回復:
我懷疑問題出在這里:
self.good = ttk.Label(self, text="Goodguy Hp:" G)
G是什么型別的?如果它是一個int你不能像你想要做的那樣將它們添加在一起,你需要將它更改為text="Goodguy Hp: " str(G),或者使用像提到的@AKX這樣的f-string
嘗試在所有四個地方更改此運算式
uj5u.com熱心網友回復:
在 python 中,您不能連接整數和字串。如果您確實嘗試這樣做,則會導致您得到以下錯誤:
can only concatenate str (not "int") to str
問題將出現在以下代碼塊中:
"Goodguy Hp:" G
和
"BadGuy Hp:" B
要解決此問題,您可以使用 @AKX 和 @vencaslac 提供的解決方案,也可以使用 %d 運算子:
"Goodguy Hp: %d" % G
"Badguy Hp: %d" % B
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/524652.html
