[英]Python Arrow Keys not responding to Paddle
Here is my problem that i just can't seem to figure out. 这是我的问题,我似乎无法弄清楚。
Here is part of my code: 这是我的代码的一部分:
from tkinter import*
import random
import time
class Paddle:
def turn_left(self, evt):
self.y = -3
def turn_right(self, evt):
self.y = 3
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0, 150, 30, 250, fill = color)
self.y = 0
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
self.canvas.bind_all('<KeyPress-a>', self.turn_left)
self.canvas.bind_all('<KeyPress-d>', self.turn_right)
def draw(self):
self.canvas.move(self.id, 0, self.y)
pos = self.canvas.coords(self.id)
if pos[1] <= 0:
self.y = 0
if pos[3] >= f00:
self.y = 0
ball = Ball(canvas, 'orange')
paddle = Paddle(canvas, "blue")
while 1:
ball.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)
and the Paddle doesn't respond to 'a' and 'd' at all. 桨完全不响应“ a”和“ d”。
Now if i take out the 'evt', run the code, and press 'a' or 'd' it gives me an 现在,如果我取出“ evt”,运行代码,然后按“ a”或“ d”,它将给我一个提示。
error, so Python knows I am pressing the keys... 错误,因此Python知道我按下了键...
Now what exactly did i do wrong? 现在我到底做错了什么?
In while
you simply forgot 在while
你根本都忘了
paddle.draw()
so keys change self.y
but it doesn't execute draw()
which moves paddle. 因此按键会更改self.y
但不会执行移动桨的draw()
。
(and name self.y
is missleading - it doesn't change paddle position directly) (并且名称self.y
具有误导性-它不会直接更改桨的位置)
Full working version with other changes (but without ball) 完整的工作版本,但有其他更改(但无球)
import tkinter as tk
import time
# --- classes ---
class Paddle:
def __init__(self, canvas, color, x, y, key_up, key_down):
self.canvas = canvas
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
# if window (and canvas) doesn't exist (yet) then it has size (1,1)
print('canvas size:', self.canvas_height, self.canvas_width)
self.id = canvas.create_rectangle(x-15, y-50, x+15, y+50, fill=color)
self.move_y = 0
self.canvas.bind_all(key_up, self.turn_left)
self.canvas.bind_all(key_down, self.turn_right)
def turn_left(self, evt):
self.move_y = -3
def turn_right(self, evt):
self.move_y = 3
def draw(self):
if self.move_y != 0:
pos = self.canvas.coords(self.id)
if pos[1] <= 0 and self.move_y < 0:
self.move_y = 0
if pos[3] >= self.canvas_height and self.move_y > 0:
self.move_y = 0
self.canvas.move(self.id, 0, self.move_y)
# --- main ---
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
# to create window and canvas
root.update()
paddle1 = Paddle(canvas, "blue", 15, 150, '<a>', '<d>')
paddle2 = Paddle(canvas, "red", 300-15, 150, '<Up>', '<Down>')
while True:
paddle1.draw()
paddle2.draw()
root.update_idletasks()
root.update()
time.sleep(0.01)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.