我的定时动作出错图形.py程序

2024-09-28 20:52:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着制作一个程序,在其中输入一个速度(像素每秒),这样窗口中的一个点就可以在x轴上以这个精确的速度移动。 我输入速度,但点不移动,空闲时不抱怨错误。你知道吗

from graphics import *
import time
win=GraphWin("Time", 600, 600)
point=Point(50, 100)
point.setFill("green")
point.draw(win)
speed=Entry(Point(100,50), 15)
speed.setText("Pixels per second")
speed.draw(win)
win.getMouse()
speed1=speed.getText()

speed1=eval(speed1)
t=0.0
time=time.clock()

if time==t+1:
   t+=1
   point.move(speed1, 0)

有人能告诉我我做错了什么吗?我使用的是python3.4


Tags: fromimport程序time错误像素win速度
2条回答

它不会移动,因为这不是一个循环:

if time==t+1:
   t+=1
   point.move(speed1, 0)

time不是==,也不是>=,所以它过去了,程序就完成了。您需要的是:

import time
from graphics import *

WINDOW_WIDTH, WINDOW_HEIGHT = 600, 600

win = GraphWin("Time", WINDOW_WIDTH, WINDOW_HEIGHT)

circle = Circle(Point(50, 200), 10)
circle.setFill("green")
circle.draw(win)

speed = Entry(Point(100, 50), 15)
speed.setText("Pixels per second")
speed.draw(win)

win.getMouse()
velocity = float(speed.getText())

t = time.clock()

while circle.getCenter().x < WINDOW_WIDTH:
    if time.clock() >= t + 1:
        t += 1
        circle.move(velocity, 0)

我用了一个更大的物体,因为它太难看到1像素的亮绿点移动。你知道吗

time.clock()返回的秒数是一个浮点数。它恰好等于t+1的可能性很低,以至于你的点很少移动。不要使用==,而是使用>=

if time >= t + 1:
    t += 1
    point.move(speed1, 0)

相关问题 更多 >