我正在製作一個菜單,該菜單在由Raspberry Pi供電的液晶顯示屏上運行。我正在嘗試使用線程模塊使LCD上的文本更新,直到菜單位置改變。循環一個函數,直到調用另一個函數
該菜單由當菜單位置改變時調用的函數列表組成。 switch_menu()
函數使用事件處理函數從類外部調用,並用於調用正確的菜單函數。通過其中一些功能(item2
);我想讓他們循環,並與他人(item1
);只顯示靜態文本。重要的是,當再次調用switch_menu()
時,它們會停止循環。我怎樣才能做到這一點?
(這裏是我的代碼的簡化版本)
class Menu:
def __init__(self):
self.LCD = Adafruit_CharLCD()
self.m_pos = 0
self.items = [self.item1,self.item2]
self.switch_menu(0)
def switch_menu(self,operation):
# 2. And here I want to stop it.
m_pos = self.m_pos
pos = m_pos
max_pos = len(self.items) - 1
m_pos = self.loop_selection(pos,max_pos,operation)
# 1. Here I want to start looping the function below.
self.items[m_pos]()
self.m_pos = m_pos
def loop_selection(self,pos,max_pos,operation):
if pos >= max_pos and operation == 1:
pos = 0
elif pos <= 0 and operation == -1:
pos = max_pos
else:
pos += operation
return pos
def item1(self):
self.LCD.clear()
text = "item1"
self.LCD.message(text)
def item2(self):
while True:
self.LCD.clear()
text = "item2"
self.LCD.message(text)
time.sleep(10)
感謝您的快速回復。然而,我想到了這一點,如果功能在菜單改變時正在休眠,該計劃似乎沒有反應。我也不確定在哪裏放置多線程代碼以及我應該如何使用它。 –
不直接關於你的問題,你可以考慮的一件小事是_loop_selection_嘗試利用'pos =(pos + 1)%(max_pos + 1)'。 –
關於多線程問題,每個事件觸發一個新線程將調用_switch_menu_? –