循环由Tkinter按钮触发,并由另一个结束

时间:2018-09-06 22:10:20

标签: python tkinter python-3.7

以下代码将显示一个小的Tkinter用户界面,但是我的按钮不会触发名为copy_loop的循环。我已经尝试了几个小时,但无法弄清楚该如何解决。任何帮助将不胜感激。

import tkinter as tk
import threading

class App():
    def __init__(self, master):
        self.isrunning = False

        self.button1 = tk.Button(main, text='start')
        self.button1.bind = ("<Button-1>", self.startrunning)
        self.button1.pack()

        self.button2 = tk.Button(main, text='stop')
        self.button2.bind = ("<Button-1>", self.stoprunning)
        self.button2.pack()

    def startrunning(self, event):
        self.isrunning = True
        t = threading.Thread(target=self.copy_loop)
        t.start()

    def stoprunning(self, event):
        self.isrunning = False

    def copy_loop(self):
        while self.isrunning:
            print("Running...")

main = tk.Tk()
app = App(main)
main.mainloop()

2 个答案:

答案 0 :(得分:2)

您有一个等号,不应有一个等号。该命令应为:

self.button1 = tk.Button(main, text='start')
self.button1.bind("<Button-1>", self.startrunning)

或者更加整洁:

self.button1 = tk.Button(main, text='start', command=self.startrunning)

并且您的方法签名应具有event=None

def startrunning(self, event=None):

或更灵活:

def startrunning(self, *args):

答案 1 :(得分:2)

bind是一个函数,而不是一个属性。您在哪里:

self.button1.bind = ("<Button-1>", self.startrunning)

您实际上是对实例上的bind函数进行覆盖。现在是一个元组。

相反,请执行以下操作:

self.button1.bind("<Button-1>", self.startrunning)

button2也是如此。