如何在Tkinter的事件循环中运行自己的代码? [英] How do you run your own code alongside Tkinter's event loop?

查看:1091
本文介绍了如何在Tkinter的事件循环中运行自己的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的弟弟刚刚进入编程,对于他的科学博览会项目,他正在模拟一群鸟儿在天空中。他的大部分代码都是写的,它的效果很好,但是每一刻都需要移动。



然而,时间为自己的事件循环,所以他的代码不会运行。执行 root.mainloop()运行,运行并保持运行,唯一运行的是事件处理程序。



有没有办法让他的代码与mainloop一起运行(没有多线程,这很困惑,这应该是简单的),如果是这样,那是什么?



现在,他想出了一个丑陋的黑客,将他的 move()函数绑定到< b1-motion> ,所以只要他按住按钮并摆动鼠标就行了。但是必须有一个更好的方法。

解决方案

在之后使用方法在 Tk 对象:

 从tkinter import * 

root = Tk()

def task():
print(hello)
root.after(2000,task)#reschedule event in 2秒

root.after(2000,task)
root.mainloop()

以下是方法后的的声明和文档:

  b $ b函数将被调用附加参数
作为函数调用的参数,返回
标识符,以使用after_cancel取消调度。


My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move every moment.

Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing root.mainloop() runs, runs, and keeps running, and the only thing it runs is the event handlers.

Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?

Right now, he came up with an ugly hack, tying his move() function to <b1-motion>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.

解决方案

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

这篇关于如何在Tkinter的事件循环中运行自己的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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