我想在Pythonclass中用canvas畫出一個長方形并用鍵盤中的左右按鍵讓它移動,但是不動
代碼入下:from tkinter import *class main:class Rectangle: def __init__(self,canvas,color): self.canvas = canvas self.id = canvas.create_rectangle(30,80,45,90,fill=color) self.x = 0 self.canvas_width = self.canvas.winfo_width() self.canvas.bind_all('<KeyPress-Left>',self.turn_left) self.canvas.bind_all('<KeyPress-Right>',self.turn_right) def draw(self): self.canvas.move(self.id,self.x,0) pos = self.canvas.coords(self.id) if pos[0] <= 0:self.x = 0 elif pos[2] >= self.canvas_width:self.x = 0 def turn_left(self,evt): self.x = -5 def turn_right(self,evt): self.x = 5root = Tk()root.title('Exterminate Ball')root.resizable(0, 0)canvas = Canvas(root,width=90,height=90,bg='black',bd=0)canvas.pack()rectangle = Rectangle(canvas,'silver')rectangle.draw()root.mainloop()(Python 3.7)
一個簡單的問題,,你self.x = -5 /self.x = 5 后沒有重新畫圖,,圖形當然沒有變化了,加兩個語句就可以了