我撰寫了一個代碼,在按住按鈕時回圈執行一個函式,并在釋放按鈕時停止執行。見下文。
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.sch_plus_button = tk.Button(self, text="S ", command=self.sch_plus_callback)
self.sch_plus_button.pack()
self.sch_plus_button.bind('<Button-1>', self.sch_plus_callback)
self.sch_plus_button.bind('<ButtonRelease-1>', self.button_stop_callback)
def button_stop_callback(self, event):
self.after_cancel(repeat)
def sch_plus_callback(self, *args):
global repeat
try:
# TODO find right time to send data to keep RELE ON
repeat = self.after(200, self.sch_plus_callback, args[0])
except IndexError:
pass
self.ser.write(b'\x02\x56\x81\x80\x80\x80\x80\x80\x39\x35\x04')
現在,只要sch_plus_callback函式基本上總是做同樣的事情,獨立地通過我要按下的命令,唯一改變的是字串ser.write(它必須根據我按下的按鈕而改變)我會想知道是否有辦法發送一個論點self.sch_plus_button.bind('<Button-1>', self.sch_plus_callback("button_1")),然后在我的點贊中獲取sch_plus_callback論點
def sch_plus_callback(self, *args):
global repeat
try:
# TODO find right time to send data to keep RELE ON
repeat = self.after(200, self.sch_plus_callback(args[0]), args[1])
except IndexError:
pass
self.ser.write(string_to_send(args[0]))
我已經嘗試了下面的代碼,但是因為我的代碼是如何撰寫的,所以它會觸發RecursionError: maximum recursion depth exceeded,所以我不知道如何解決這個問題
uj5u.com熱心網友回復:
我找到的解決方案是
self.sch_plus_button = tk.Button(self, text="S ", command=lambda: self.sch_plus_callback('sch_plus'))
self.sch_plus_button.pack()
self.sch_plus_button.bind('<Button-1>', lambda event: self.sch_plus_callback('sch_plus', event))
self.sch_plus_button.bind('<ButtonRelease-1>', self.button_stop_callback)
def button_stop_callback(self, event):
self.after_cancel(repeat)
def sch_plus_callback(self, *args):
global repeat
logging.info("args are " str(args))
try:
repeat = self.after(300, self.sch_plus_callback, args[0], args[1])
except IndexError:
pass
args[0]指示按下按鈕和args[1]要處理的事件的引數在哪里
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/475797.html
