运行程序时如何开始上课?

时间:2019-03-27 16:20:55

标签: python tkinter

我想创建一个正方形移动的小游戏。有人在运行程序时知道如何使类开始吗?

这是课程

class Player:
    def __init__(self, event):
        self.player = self.canvas.create_rectangle(240, 240, 260, 260, 
        fill="blue", outline="dark blue")
        canvasx = canvas.winfo_width()
        canvasy = canvas.winfo_height()
        canvas.bind_all("<KeyPress-Up>", move)
        canvas.bind_all("<KeyPress-w>", move)
        canvas.bind_all("<KeyPress-Down>", move)
        canvas.bind_all("<KeyPress-s>", move)
        canvas.bind_all("<KeyPress-Right>", move)
        canvas.bind_all("<KeyPress-d>", move)
        canvas.bind_all("<KeyPress-Left>", move)
        canvas.bind_all("<KeyPress-a>", move)
    def move(event):
        if event.keysym == "Up" or event.keysym == "w":
            canvas.move(1, 0, -5)
        elif event.keysym == "Down" or event.keysym == "s":
            canvas.move(1, 0, 5)
        elif event.keysym == "Right" or event.keysym == "d":
            canvas.move(1, 5, 0)
        else:
            canvas.move(1, -5, 0)

canvas = Canvas(tk, width=500, height=500, bg="silver")
canvas.pack()

这个while循环应该使函数运行,但是不会

while True:
    Player.__init__
    Player.move
    tk.update()
    time.sleep(0.01)

1 个答案:

答案 0 :(得分:2)

此:

Player.__init__
Player.move
tk.update()
time.sleep(0.01)

不是您创建类实例的方式。当您放置Player.__init__时,实际上并没有在调用构造函数。您基本上只是在说它存在。与Player.move相同。您必须实际调用该方法。替换这两行:

playerOne = Player(canvas)
playerOne.move()

现在playerOnePlayer类的实例。

除此之外,Player构造函数中还有一个附加问题。

def __init__(self, event):
    self.player = self.canvas.create_rectangle(240, 240, 260, 260, 
    fill="blue", outline="dark blue")

当您引用self.canvas时,没有self.canvas。您必须先分配它,然后才能使用它。而且您似乎没有在任何地方使用self.player。我不确定您要做什么,但是尝试这样的事情:

def __init__(self, canvas):
    self.canvas = canvas.create_rectangle(240, 240, 260, 260, 
    fill="blue", outline="dark blue")

然后使用以下内容替换您的move方法定义:

def move(event=None):
    if event == None:
        return
    if event.keysym == "Up" or event.keysym == "w":
        canvas.move(1, 0, -5)
    elif event.keysym == "Down" or event.keysym == "s":
        canvas.move(1, 0, 5)
    elif event.keysym == "Right" or event.keysym == "d":
        canvas.move(1, 5, 0)
    else:
        canvas.move(1, -5, 0)

在您的Player类之外定义。