|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
当移动到左右边界时会消失,这个怎么解决?我的目的是移动到左右边界是固定,比如移动到左边,再按左方向键就不动了,固定在左边边界
from tkinter import *
import random
import time
class Paddle:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
self.canvas.move(self.id, 200, 300)
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)
#self.canvas.bind_all('<KeyRelease-Left>', self.key_up)
#self.canvas.bind_all('<KeyRelease-Right>', self.key_up)
def turn_left(self, evt):
self.x = -5
def turn_right(self, evt):
self.x = 5
def key_up(self,evt):
self.x = 0
def draw(self):
self.canvas.move(self.id, self.x, 0)
pos = self.canvas.coords(self.id)
if pos[0] <= 0:
#这个错在哪里,求解
#self.x = 0
self.canvas.move(self.id, 0, 300)
elif pos[2] >= self.canvas_width:
#这个错在哪里,求解
#self.x = 0
self.canvas.move(self.id, 400, 300)
tk = Tk()
tk.title("Game")
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
tk.update()
paddle = Paddle(canvas, 'blue')
while 1:
paddle.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)
|
|