我在Connect
中有一个Disconnect
按钮和一个main.py
按钮。
启用Connect
按钮,禁用Disconnect
按钮。当我单击Connect
按钮时,将调用lambda表达式,该表达式将切换另一个文件toggle_device_connection
中另一个类Modbus
中的设备连接(modbus.py
)。我紧随其后的是另一个lambda表达式,它将禁用连接按钮并启用Disconnect
按钮,反之亦然(toggle_buttons
)。
问题是,每当第一个lambda表达式中的连接引发异常(例如连接不成功)时,它仍会将按钮从启用切换为禁用,这是不希望的。
示例代码:
modbus = modbus class
connect_button = Button(parent, text='Connect', command= lambda: (modbus.toggle_device_connection(state=1),
toggle_buttons(state=1)))
disconnect_button = Button(parent, text='Disconnect', command= lambda: (modbus.toggle_device_connection(state=0),
toggle_buttons(state=0)))
问题是:如何将数据从一类传输到另一类? (在此示例中)
答案
我认为我的答案如下:
# Main.py
self.modbus = Modbus()
connect_button = Button(parent, text='Connect', command= lambda: modbus.toggle_device_connection(state=True)
def toggle_buttons(self, state=False):
if state:
# Disable Connect
# Enable Disconnect
else:
# Enable Connect
# Disable Disconnect
self.modbus.device_connection = lambda bool: toggle_buttons(state=bool)
# Modbus.py
self.device_connection = lambda bool: 'Connection unsuccessful'
def toggle_device_connection(self):
...
if success:
return True
else:
return False
...
答案 0 :(得分:0)
尝试使用功能。
... lambda:function(params)...
执行功能
功能(参数): 尝试: ... 例外,例如e: 打印(e) do_something()
答案 1 :(得分:0)
更多代码,但是您可以使用tk.BooleanVar
,其中trace_add
可以监听变量值的变化,并且可以根据成功的情况来切换按钮状态/连接失败:
也许是这样的:
import random
import tkinter as tk
def connection():
# has no knowledge of your GUI
conn = random.choice([False, True, True]) # simulate a network failure 1/3rd of the tim
status = 'successful' if conn else 'fail'
print(f'connected {status}')
return conn # not a callback, so the return value can be used
def connect_callback():
print('...connecting')
# use the return value to alter the connection_status
# maybe defend it in a try / except block
connection_status.set(connection())
def disconnect_callback():
print('...disconnecting')
connection_status.set(False)
def set_buttons_aspect(*args):
if connection_status.get():
btn1.config(state=tk.DISABLED)
btn2.config(state=tk.NORMAL)
else:
btn1.config(state=tk.NORMAL)
btn2.config(state=tk.DISABLED)
root = tk.Tk()
connection_status = tk.BooleanVar(root)
connection_status.set(False)
btn1 = tk.Button(root, text='connect', command=connect_callback)
btn1.pack()
btn2 = tk.Button(root, text='disconnect', command=disconnect_callback)
btn2.pack()
set_buttons_aspect()
connection_status.trace_add('write', set_buttons_aspect)
# listens to changes in connection_status and calls set_buttons_aspect when it occurs
root.mainloop()