蟒蛇和放大器; PyGTK的:停止,而在按一下按钮 [英] Python&PyGTK: Stop while on button click

查看:205
本文介绍了蟒蛇和放大器; PyGTK的:停止,而在按一下按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

在code为startLoop高清将是:

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.

你有没有使用 切换按钮 而不是 的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.

下面是启动和控制依赖于一个切换按钮的状态的线程的例子(替换引发点击切换按钮按钮如果你想一个普通的按钮):

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.

这篇关于蟒蛇和放大器; PyGTK的:停止,而在按一下按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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