这是我的问题,我似乎无法弄清楚。
以下是我的代码的一部分:
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)
并且Paddle没有回复&#39; a&#39;并且&#39; d&#39;一点都不。
现在,如果我拿出“退出”,请运行代码,然后按“&#39; a&#39;或者&#39; d&#39;它给了我一个
错误,所以Python知道我在按键......
现在我究竟做错了什么?
答案 0 :(得分:1)
在while
中,您忘记了
paddle.draw()
因此密钥更改为self.y
,但它不会执行移动操纵杆的draw()
。
(名称self.y
具有误导性 - 它不会直接改变桨位)
包含其他更改的完整工作版本(但没有球)
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)