我无法配置我的失败。我总是希望当我点击按钮 E 时,它从 10 中扣除一个失败

I can't config my fails. I want always when I click button E, that it deduct fails from 10 by one

我有问题。我无法配置我的失败。我总是希望当我点击按钮 E 时,它从 10 中减去一个失败。请尝试解决它!

代码:

fails = str(10)

def wrong():
    wrong_label = Label(wrong_frame,
                        text='wrong letter!!',
                        bg='red')
    global fails
 #   new_integer = fails - 1
    fails -= str(1)
    l1.config(text=new_integer)


window = Tk()


alpha_e = Button(window,
                 text='E',
                 bg='blue',
                 command=wrong)
alpha_e.place(y=50,x=250)


wrong_frame = Frame(window,
                    bg="red",
                    bd=2,
                    relief=SUNKEN
                    )
wrong_frame.place(x=500,y=250)

wrong_always = Label(wrong_frame,
                     text='You have only ' + fails + ' tries more!',
                     )
wrong_always.pack()


window.mainloop()

您的问题是您将失败变量存储为字符串而不是整数。您不能对字符串进行数学运算,它必须是数字数据类型,例如 integerfloat。但是,您应该使用 str(<your variable>).

将变量转换为标签中的字符串

代码:

fails = 10 #store the variable as an int

def wrong():
    wrong_label = Label(wrong_frame,
                        text='wrong letter!!',
                        bg='red')
    global fails

    fails -= 1 #since its an int you can now do math with it


window = Tk()


alpha_e = Button(window,
                 text='E',
                 bg='blue',
                 command=wrong)
alpha_e.place(y=50,x=250)


wrong_frame = Frame(window,
                    bg="red",
                    bd=2,
                    relief=SUNKEN
                    )
wrong_frame.place(x=500,y=250)

wrong_always = Label(wrong_frame,
                     text='You have only ' + str(fails) + ' tries more!',
                     )#convert it to a string on display with str()
wrong_always.pack()


window.mainloop()```

有关 python 数据类型的更多信息,请转到 here