Tkinter和线程 [英] Tkinter and threads

查看:97
本文介绍了Tkinter和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想做的是创建一个tkinter窗口,然后在不重新打开GUI的情况下将其放置在屏幕上.我面临的第一个问题是线程似乎无法正常工作.该程序选择仅运行deplacewindow函数,而忽略thread.start行下面的代码.有可能解决这个问题吗?还是有更好的方法可以在屏幕上移动tkinter窗口?

So, what I am trying to do is to create a tkinter window and then deplace it across the screen without reopening the GUI. The first problem I am facing is that the threading doesn't seem to work. The program chooses to only run the deplacewindow function and ignoring the code below the thread.start line. Is it possible to fix this? Or is there a better way to displace a tkinter window across the screen?

这是代码:

import tkinter as tk
import time,threading

root = tk.Tk() # create a Tk root window

w = 200 # width for the Tk root
h = 200 # height for the Tk root

# get screen width and height
sw = root.winfo_screenwidth() # width of the screen
sh = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for the Tk root window to appear on the
# bottom right of the screen
x = sw - w - 20
y = sh - h - 80
print (sw,"-",w,"    ",sh,"-",h)
print (x,y)


# set the dimensions of the screen 
# and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

def mainloop():
    global root
    root.mainloop() # starts the mainloop
def deplaceWindow():
    global root,x
    print ("Starting loop")
    while 1:
        time.sleep(1)
        x-=10
        print (x)
        #root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
print ("starting thread")
threading.Thread(target=deplaceWindow()).start()
print ("starting mainloop")
mainloop()

推荐答案

似乎您想要的是一个 timer 事件. TkInter为此使用了 after 方法:

It seems what you want is a timer event. TkInter uses the after method for this:

root = tk.Tk() # create a Tk root window
x = -10

...

def mainloop():
    global root
    print ("Starting loop")
    # calls to other root methods must come before call to mainloop().
    root.after(1000, deplaceWindow)
    root.mainloop() # starts the mainloop

def deplaceWindow():
    global root,x
    print (x)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))
    x -= 10
    root.after(1000, deplaceWindow)   # 1000 miliseconds

if __name__=="__main__":
    print ("starting mainloop")
    mainloop()


此外:与GUI线程的任何交互都不能来自其他线程(如@Bryan_Oakley所述).您可以在主脚本中有一个函数,该函数使用root.after方法调度事件,但不能从外部线程直接调用.


Additionally: Any interaction with the GUI thread cannot be from other threads (as @Bryan_Oakley explained). You can have a function in your main script which schedules events using the root.after method, but not a direct call from the foreign thread.

这篇关于Tkinter和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆