【发布时间】:2022-01-23 00:15:38
【问题描述】:
from tkinter import *
import random
import time
tk = Tk()
cv = Canvas(tk, width = 1000, height = 500)
cv.configure(bg = "black")
p1 = cv.create_rectangle(975, 200, 965, 300, fill = "white", outline = "white")
p2 = cv.create_rectangle(25, 200, 35, 300, fill = "white", outline = "white")
ball = cv.create_rectangle(495, 245, 505, 255, fill = "white", outline = "white")
directionx = [13, -13]
directiony = [13, 12, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9,
-10, -11, -12, -13]
dx = (directionx[random.randint(0,len(directionx)-1)])
dy = (directiony[random.randint(0,len(directiony)-1)])
cv.pack()
def p1up():
p1.y = -15
def p1down():
p1.y = 15
cv.bind_all('<Key-Press-w>', p1.y + 15)
while True:
cv.move(ball, dx, dy)
tk.update()
time.sleep(0.016666)
我只想用 w 键移动 p1 桨。我已经尝试了各种键绑定配置,但它似乎不起作用,要么我得到一个错误,要么桨只是不动
【问题讨论】:
-
您既没有更新
dx也没有更新dy,您只需在开始时设置它们的值就可以了,而且p1没有属性y所以你不能这样做p1.y,我建议你看一些pygame教程,因为pygame是用于游戏的,这些教程涵盖了这些基础知识(特别是因为你甚至没有使用mainloop而是你自己的自定义循环(顺便说一句,你不应该这样做)不做,你应该使用mainloop)) 并且在导入时不要使用* -
您可以在stackoverflow.com/help/how-to-ask 中找到有关编写问题的提示,例如,您的标题太长,应该是问题正文中的第一句话,而不是标题。