Python&PyGTK:单击按钮时停止 [英] Python&PyGTK: Stop while on button click

查看:30
本文介绍了Python&PyGTK:单击按钮时停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些应用程序,我想在单击按钮时创建 while 循环,如果再次单击它以停止它.这是按钮的代码:

I'm working on programming some application and I would like to create while loop when button is clicked and if it's clicked again to stop it. This is the code for button:

self.btnThisOne = gtk.Button("This one")
self.btnThisOne.connect("clicked", self.startLoop)

startLoop def 的代码是:

The code for startLoop def would be:

def startLoop(self):
    while self.btnThisOne?(is_clicked)?:
        #do something

怎么做?

推荐答案

不幸的是,您不能在应用程序的主线程中运行一个不受约束的 while 循环.这会阻塞主要的 gtk 事件循环 并且您将无法处理更多事件.您可能想要做的是生成一个线程.

Unfortunately, you cannot just have an unconstrained while loop running in the main thread of your application. That would block the main gtk event loop and you won't be able to process any more events. What you probably want to do is spawn a thread.

您是否考虑过使用 ToggleButton 代替GtkButton?最接近 is_clicked 方法的是 is_active,你会在切换按钮中找到它.

Have you considered using a ToggleButton instead of GtkButton? The closest thing to an is_clicked method is is_active and you'll find that in toggle buttons.

以下是根据切换按钮的状态启动和控制线程的示例(将 triggered 替换为 clicked,将 ToggleButton 替换为 Button 如果你想要一个普通的按钮):

Here's an example of starting and controlling a thread depending on the state of a toggle button (replace triggered with clicked and ToggleButton with Button if you want a regular button):

import gtk, gobject, threading, time

gobject.threads_init()

window = gtk.Window()
button = gtk.ToggleButton('Start Thread')

class T(threading.Thread):
    pause = threading.Event()
    stop = False

    def start(self, *args):
        super(T, self).start()

    def run(self):
        while not self.stop:
            self.pause.wait()
            gobject.idle_add(self.rungui)
            time.sleep(0.1)

    def rungui(self):
        pass # all gui interaction should happen here

thread = T()
def toggle_thread(*args):
    if not thread.is_alive():
        thread.start()
        thread.pause.set()
        button.set_label('Pause Thread')
        return

    if thread.pause.is_set():
        thread.pause.clear()
        button.set_label('Resume Thread')
    else:
        thread.pause.set()
        button.set_label('Pause Thread')

button.connect('toggled', toggle_thread, None)

window.add(button)
button.show()
window.show()
gtk.main()

这个 PyGTK 常见问题解答 可能证明有帮助.干杯.

This PyGTK FAQ answer might prove helpful. Cheers.

这篇关于Python&PyGTK:单击按钮时停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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