【问题标题】:tkinter and thread argumentstkinter 和线程参数
【发布时间】:2019-02-25 07:21:02
【问题描述】:

我有一个用python tkinter写的简单的ui,它只有一个按钮。

我在这里发现了一个问题,如果按钮命令被定向到一个函数,其中包括创建一个实例来执行它的方法。然而,当我运行这个程序时,我的 pycharm 告诉我我正在将一个位置参数传递给该方法,而我从未这样做过:

TypeError: tell_time() 接受 0 个位置参数,但给出了 1 个

由于某些原因,我必须将方法保留在类中。谁能告诉我如何让该方法运行?太感谢了!

def build_ui():

    root = Tk()
    root.title("Auto Hedger")
    root.geometry("640x480")

    btn1 = Button(root, text="get data", command=testing1)
    btn1.pack()


    root.mainloop()

class test_object():
    def tell_time():
        print(datetime.datetime.now())

def testing1():
    aaa = test_object()
    t1000 = Thread(target=aaa.tell_time, args=[])
    t1000.start()


if __name__ == '__main__':

    t_root = Thread(target=build_ui)
    t_root.start()

【问题讨论】:

    标签: python tkinter parameter-passing


    【解决方案1】:

    您的tell_time 方法需要self 作为参数,因为它是类方法而不是函数。添加它应该可以正常工作。 试试这个:

    from threading import Thread
    from tkinter import *
    import datetime
    
    def build_ui():
        root = Tk()
        root.title("Auto Hedger")
        root.geometry("640x480")
    
        btn1 = Button(root, text="get data", command=testing1)
        btn1.pack()
    
        root.mainloop()
    
    class test_object():
        def tell_time(self):
            print(datetime.datetime.now())
    
    def testing1():
        aaa = test_object()
        t1000 = Thread(target=aaa.tell_time, args=[])
        t1000.start()
    
    if __name__ == '__main__':
        t_root = Thread(target=build_ui)
        t_root.start()
    

    【讨论】:

    • 或者把@staticmethod放在你的def tell_time()之前。
    猜你喜欢
    • 2014-12-29
    • 2014-07-30
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    相关资源
    最近更新 更多