【问题标题】:i am making old school pong on tkinter, and i cant figure out how to make the paddle move我在 tkinter 上做老式乒乓球,我不知道如何让桨移动
【发布时间】: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 中找到有关编写问题的提示,例如,您的标题太长,应该是问题正文中的第一句话,而不是标题。

标签: python tkinter


【解决方案1】:

我已经修复了代码:

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
    cv.move(p1, 0, -15) # 0 is x parameter
def p1down():
    p1.y = 15
cv.bind_all('<KeyPress-w>', p1.y + 15) # Not <Key-Press-w>
while True:
    cv.move(ball, dx, dy)
    tk.update()
    time.sleep(0.016666)

这将使球拍移动,但它仍然不会让球反弹。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多