Tkinter events outside mainloop?

In the program I am writing, there is a tkinter window that is constantly loaded with data manually, and is not part of mainloop. It should also track the location of the mouse. I havn't found a workaround for mouse tracking outside mainloop yet, but if you have one, please let me know.

from Tkinter import * import random import time def getCoords(event): xm, ym = event.x, event.y str1 = "mouse at x=%dy=%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() 
+4
source share
1 answer

There is no way. Mouse movement is represented by a graphical interface as a series of events. To handle events, the loop cycle must be started.

In addition, you will almost never sleep inside a GUI application. All that happens is to freeze the GUI while you sleep.

Another hint: you only need to create an icicle once; To do this, you can use the move method on the canvas.

If you are having trouble understanding event-based programming, the solution is not to avoid the event loop, but the solution is to find out how the event loops work. You cannot create a graphical interface without it.

+6
source

All Articles