【问题标题】:Starting and stopping thread with python and tkinter使用 python 和 tkinter 启动和停止线程
【发布时间】:2020-08-09 16:50:24
【问题描述】:

我一直在尝试使用此答案提供的代码:

Terminate the Thread by using button in Tkinter

但是每次我运行它时,当我单击按钮时都会收到以下错误消息:

self.stop_threads.clear() AttributeError:“事件”对象没有属性“清除”

self.stop_threads.set() AttributeError:“事件”对象没有属性“设置”

我知道这一定很简单,但我真的很难过任何建议/指针都将不胜感激。

from threading import Thread,Event
from subprocess import call
from tkinter import *

import tkinter as tk

class Controller(object):
    def __init__(self):
        self.thread1 = None
        self.thread2 = None
        self.stop_threads = Event()

    def loop1(self):
        while not self.stop_threads.is_set():
            call(print('Thread Loop 1'))

    def loop2(self):
        while not self.stop_threads.is_set():
            call(print('Thread Loop 2'))

    def combine(self):
        self.stop_threads.clear()
        self.thread1 = Thread(target = self.loop1)
        self.thread2 = Thread(target = self.loop2)
        self.thread1.start()
        self.thread2.start()

    def stop(self):
        self.stop_threads.set()
        self.thread1.join()
        self.thread2.join()
        self.thread1 = None
        self.thread2 = None

if __name__ == '__main__':
    master = tk.Tk()
    master.title("Thread Start Stop Exercise")
    master.geometry("1024x600")

    control = Controller()

    btn1 = Button(master, text="Start Thread", width=16, height=5, command=control.combine)
    btn1.grid(row=2,column=0)
    btn2 = Button(master, text="Stop Thread", width=16, height=5, command=control.stop)
    btn2.grid(row=3,column=0)

    master.mainloop()

【问题讨论】:

  • 实际上你使用的是tkinter.Event,而不是threading.Event,因为from tkinter import *这一行在from threading import Thread, Event之后。交换两条线。 from tkinter import * 不是导入 tkinter 的好习惯。
  • 谢谢你,我知道我做的很愚蠢!非常感谢

标签: tkinter event-handling python-multithreading python-3.8


【解决方案1】:

这里的问题是tkinter 也有一个tkinter.Event 对象,它被用来代替threading.Event,因为tkinter 是在threading 之后导入的。

您可以尝试换行:

from subprocess import call
from tkinter import *
from threading import Thread,Event

或者,具体说明您需要从 tkinter 导入的内容,或者根本不使用通配符导入以避免全局命名空间污染和此类错误。在所有命令前加上 tk 前缀,当您使用 Tkinter 类、ttk 类或其他类时,它会使代码完全清晰,不会有歧义。

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多