如果这是一个多余的帖子我很抱歉,但我花了几个小时嗅探StackOverflow和其他来源的解决方案,这就是我最终的结果。 AFAIK它应该工作。
简单地说,我无法理解为什么我的变量不会多次更新。当我运行这个程序时,它从'0.0'开始并更新为实际值(在time.sleep(5)之后),但只有一次。从理论上讲,它应该实时更新......
我意识到你无法使用我的确切Modbus从设备等重新创建我的开发环境,但是flow_unpack
是一个“好”变量,因为它打印到Tkinter窗口一次。如果它不好,它将返回ValueError或其他东西。问题是:为什么不更新?
import tkinter as tk
import time
import minimalmodbus
import serial
import struct
root = tk.Tk()
root.resizable(width=False, height=False)
root.geometry('{}x{}'.format(500, 500))
i = minimalmodbus.Instrument('/dev/ttyUSB0', 1)
i.serial.baudrate = 9600
i.serial.bytesize = 8
i.serial.parity = serial.PARITY_ODD
i.serial.stopbits = 1
i.serial.timeout = 1
i.debug = False
var = tk.DoubleVar()
label = tk.Label(root, textvariable=var)
label.pack()
mass_flow_rate = i.read_registers(registeraddress=246, numberOfRegisters=2,
functioncode=3)
flow_ = [mass_flow_rate[0], mass_flow_rate[1]]
flow_pack = struct.pack('HH', flow_[0], flow_[1])
flow_unpack = round(struct.unpack('f', flow_pack)[0], 4)
def function():
global flow_unpack
var.set(flow_unpack)
root.update()
time.sleep(5)
root.after(2000, function)
root.mainloop()
答案 0 :(得分:1)
在您的代码中更改此内容
def function():
global flow_unpack
var.set(flow_unpack)
root.after(2000, function) # just add this for further calls
# root.update() -> not needed, see Brian comment.
# time.sleep(5) -> do you really need this?
# you will block the tkinter mainloop and your UI.