主循环外的事件?

2024-09-28 23:03:17 发布

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

我正在编写的程序有一个tkinter窗口,它不断地被手动输入数据,而不是主循环的一部分。它还需要跟踪鼠标的位置。我还没有找到一个解决办法来跟踪鼠标外的主循环,但如果你有一个请告诉。在

from Tkinter import *
import random
import time

def getCoords(event):
    xm, ym = event.x, event.y
    str1 = "mouse at x=%d  y=%d" % (xm, ym)
    print str1

class iciclePhysics(object):
    def __init__(self, fallrange, speed=5):
        self.speed = speed
        self.xpos = random.choice(range(0,fallrange))
        self.ypos = 0

    def draw(self,canvas):
        try:
            self.id = canvas.create_polygon(self.xpos-10, self.ypos, self.xpos+10, self.ypos, self.xpos, self.ypos+25, fill = 'lightblue')
        except:
            pass

    def fall(self,canvas):
        self.ypos+=self.speed
        canvas.move(self.id, 0, self.ypos)



root = Tk()
mainFrame = Frame(root, bg= 'yellow', width=300, height=200)
mainFrame.pack()
mainCanvas = Canvas(mainFrame, bg = 'black', height = 500, width = 500, cursor = 'circle')
mainCanvas.bind("<Motion>", getCoords)
mainCanvas.pack()

root.resizable(0, 0)
difficulty = 1500
#root.mainloop()
currentIcicles = [iciclePhysics(difficulty)]
root.update()
currentIcicles[0].draw(mainCanvas)
root.update_idletasks() 
time.sleep(0.1)
currentIcicles[0].fall(mainCanvas)
root.update_idletasks() 
tracker = 0
sleeptime = 0.04


while True:
    tracker+=1
    time.sleep(sleeptime)
    if tracker % 3 == 0 and difficulty > 500:
        difficulty -= 1
    elif difficulty <= 500:
        sleeptime-=.00002
    currentIcicles.append(iciclePhysics(difficulty))
    currentIcicles[len(currentIcicles)-1].draw(mainCanvas)

    for i in range(len(currentIcicles)):
        currentIcicles[i].fall(mainCanvas)
        root.update_idletasks()

    for i in currentIcicles:
        if i.ypos >= 90:
            currentIcicles.remove(i)
    root.update_idletasks()

Tags: importselfeventtimedefupdaterootcanvas
1条回答
网友
1楼 · 发布于 2024-09-28 23:03:17

没办法。鼠标移动作为一系列事件呈现给GUI。为了处理事件,必须运行事件循环。在

此外,您应该在GUI应用程序中几乎从不睡觉。所做的只是在睡眠期间冻结GUI。在

另一个提示:您只需要创建一次冰柱;要使其掉落,可以使用画布的move方法。在

如果您在理解基于事件的编程时遇到问题,解决方法不是避免事件循环,而是了解事件循环如何工作。没有它你几乎不能创建一个GUI。在

相关问题 更多 >