2013-09-28 238 views
1

我试图用pywinusb同时从HID读取数据,然后用该数据更新tkinter窗口。当发生HID方面的事情时,我希望我的tkinter窗口立即反映出这一变化。Python + Tkinter:从HID读取数据并同时更新tkinter标签

下面是代码:

import pywinusb.hid as hid 
from tkinter import * 

class MyApp(Frame): 
    def __init__(self, master):   
     super(MyApp, self).__init__(master) 
     self.grid() 
     self.setupWidgets() 
     self.receive_data() 

    def setupWidgets(self): 
     self.data1 = StringVar() 
     self.data1_Var = Label(self, textvariable = self.data1) 
     self.data1_Var.grid(row = 0, column = 0, sticky = W) 

    def update_data1(self, data): 
     self.data1.set(data) 
     self.data1_Var.after(200, self.update_data1) 

    def update_all_data(self, data): 
     self.update_data1(data[1]) 
     #self.update_data2(data[2]), all points updated here... 

    def receive_data(self): 
     self.all_hids = hid.find_all_hid_devices() 
     self.device = self.all_hids[0] 
     self.device.open() 
     #sets update_all_data as data handler 
     self.device.set_raw_data_handler(self.update_all_data) 

root = Tk() 
root.title("Application") 
root.geometry("600x250") 
window = MyApp(root) 
window.mainloop() 

当我运行的代码,使设备发送数据时,我得到这个错误:

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Program Files\Python 3.3\lib\tkinter\__init__.py", line 1442, in __call__ 
    return self.func(*args) 
    File "C:\Program Files\Python 3.3\lib\tkinter\__init__.py", line 501, in callit 
    func(*args) 
TypeError: update_data1() missing 1 required positional argument: 'data' 

我想我的问题是:

我如何使用HID中的当前数据持续更新标签? 如何将新数据传递给update_data1()?

编辑:我应该使用线程,以便我有一个线程接收数据,并且mainloop()线程会定期检查新数据吗?我以前没有使用过线程,但是这可能是一个解决方案吗?

如果有更好的方法来做到这一点,请让我知道。

谢谢!

回答

0

self.data1_Var.after(200, self.update_data1)是问题所在。您需要将self.update_data1的参数传递给self.data1_Var.after(例如self.data1_Var.after(200, self.update_data1, some_data))。否则,在200毫秒后,self.update_data1将被调用而不带参数,导致您看到的错误。

顺便说一句,为什么不直接编辑标签的文本,而不是把代码放在self.update_all_data。我不清楚为什么self.data1_Var.after(200, self.update_data1)是必需的,因为每当收到新数据时,update_all_data被调用,其中调用update_data1哪些更新文本。