简体   繁体   English

python tkinter:单击按钮时调用对象方法不起作用

[英]python tkinter: Calling a objects method on button click does not work

here is my sample code:这是我的示例代码:

from time import  sleep
import tkinter as tk
import threading


class Action:

    counter = 0

    def do_something(self):
        while True:
            print('Looping')
            sleep(5)


action = Action()
root = tk.Tk()

button = tk.Button(root, text='pressme harder', command=threading.Thread(target=action.do_something()).start())
button.grid(row=1, column=0)

root.mainloop()

What am I expecting?我在期待什么? I'm expecting that as soon as I click the button in the UI an new thread is running, which is looping in the background and does not interfere with the UI (or later maybe other threads doing tasks in the background)我希望只要我单击 UI 中的按钮,就会运行一个新线程,该线程在后台循环并且不会干扰 UI(或者稍后可能其他线程在后台执行任务)

What is really happening?到底发生了什么? When running the code, the method of the class is executeds immdiately and locking the procedure.运行代码时,立即执行class的方法并锁定过程。 root.mainloop() is never reached and therefore no UI is drawn root.mainloop()永远不会到达,因此不会绘制任何 UI

Alternatively I tried the following change:或者我尝试了以下更改:

button = tk.Button(root, text='pressme harder', command=threading.Thread(target=lambda: action.do_something()).start())

This behaves in the following (imho wrong) way: The method is also called immediately, without pressing the button.这表现在以下(恕我直言是错误的)方式:该方法也被立即调用,而无需按下按钮。 This time the UI is drawn but seems the be locked by the thread (UI is slow/stuttering, pressing the buttom does not work most of the time)这次绘制了 UI,但似乎被线程锁定了(UI 很慢/断断续续,大多数时候按下按钮不起作用)

Any Idea whats wrong there?知道那里出了什么问题吗? Or how do I handle this in a more stable way?或者我如何以更稳定的方式处理这个问题?

You shouldn't try to start a thread directly in the button command.您不应该尝试直接在按钮命令中启动线程。 I suggest you create another function that launches the thread.我建议您创建另一个启动线程的 function。

from time import sleep
import tkinter as tk
import threading


class Action:
    counter = 0
    def do_something(self):
        while True:
            print('Looping')
            sleep(2)
            print("Finished looping")
            
    def start_thread(self):
        thread = threading.Thread(target=self.do_something, daemon=True)
        thread.start()


action = Action()
root = tk.Tk()

button = tk.Button(root, text='pressme harder', command=action.start_thread)
button.grid(row=1, column=0)

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM