在Python中使用命令参数时,Tkinter无法识别类

时间:2019-07-27 17:56:13

标签: python tkinter pycharm

试图在Tkinter中创建一个带有按钮的小窗口 运行Python版本3.7.4

当对象不在类中时,使用“ command =”仍然有效

from tkinter import *

master = Tk()

class enemy:
    life = 100
    def attack(self):
        self.life -= 10
        print('ouchhh') or print('arghhh')

    def checklife(self):
        if life <= 0:
            print("im dead")
        else:
            print('the enemy has' , self.life)



master.geometry('200x200')
master.title('game')

attackbutton = Button(master,text='Attack',bg="black",fg='White',command=attack)
attackbutton.pack()

checklifebutton = Button(master,text='Check enemy HP',bg="red",fg="white",command=checklife)
checklifebutton.pack()


master.mainloop()

而不是运行程序会在控制台中打印出来

attackbutton = Button(text='Attack',bg="black",fg='White',command=attack)
NameError: name 'attack' is not defined

1 个答案:

答案 0 :(得分:0)

首先,您需要确定您的课程enemy是否为1个或更多敌人设计。当前,您将life = 100定义为与实例无关的类属性。要仅为一个敌人创建生命条,请在__init__下创建它。

接下来,您需要创建enemy类的实例。您可以通过定义变量a = Enemy()来实现。

总结一切:

from tkinter import *
import random

master = Tk()

class Enemy:
    def __init__(self):
        self.life = 100
    def attack(self):
        self.life -= 10
        print (random.choice(['ouchhh','arghhh'])) #use random.choice instead to generate a random message

    def checklife(self):
        if self.life <= 0:
            print("im dead")
        else:
            print('the enemy has' , self.life)

master.geometry('200x200')
master.title('game')

a = Enemy()

attackbutton = Button(master,text='Attack',bg="black",fg='White',command=a.attack)
attackbutton.pack()

checklifebutton = Button(master,text='Check enemy HP',bg="red",fg="white",command=a.checklife)
checklifebutton.pack()

master.mainloop()