Sax*_*ute 4 python tkinter root
我正在编写的程序有一个tkinter窗口,它不断地手动提供数据,而不是作为主循环的一部分.它还需要跟踪鼠标位置.我还没有找到在mainloop之外跟踪鼠标的解决方法,但是如果你有一个,请告诉我.
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()
Run Code Online (Sandbox Code Playgroud)
没有办法.鼠标移动作为一系列事件呈现给GUI.为了处理事件,必须运行事件循环.
此外,您几乎不应该在GUI应用程序中进行睡眠.所有这一切都是在睡眠期间冻结GUI.
另一个提示:你只需要创建一次冰柱; 使它下降你可以使用move画布的方法.
如果您在理解基于事件的编程时遇到问题,解决方案就是不要避免事件循环,解决方案是了解事件循环的工作原理.没有它,你几乎无法创建GUI.