需要帮助找到使用gpio和after方法的tkinter解决方案



我正在tkinter做一个项目,这是一个问卷调查。如果你回答正确,它会把你带到最后一页,提示你按下按钮。一旦你按下那个按钮,我需要GPIO引脚设置为高电平并保持一段时间,然后切换回低电平。之后,它会带你回到主页,重新开始问卷调查。

我从time.sleep函数开始,它可以将引脚保持在高位,我已经了解到它不适合用于GUI。尽管如此,它确实对我有效,但通过测试,我发现当它在睡眠期间,按钮仍然会按下按钮,并且似乎会缓冲它们,这似乎会在第一次按下按钮后叠加。

在进行了一些搜索后,我找到了After方法,并尝试实现它,它似乎做了一些非常类似的事情。我想让这个程序尽可能万无一失,这样,如果有人不耐烦,按下两次按钮,它就不会延长持续时间并使其锁定。

我也试过在按下后禁用按钮,但我似乎无法正常工作。

这是一个窗口,它会提示你按下按钮,然后触发gpio变高,等待一段时间,然后变低。然后切换到主页面。我还让它移动鼠标,这样它就不会悬停在下一页上的按钮上

class PleasePass(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Thank you n Please press the button then proceed to tempature reading",
font=('Helvetica', 30))
label.grid(column=0, row=0, padx=110, pady=200)
button1 = tk.Button(self, text="Ready to Proceed", height=3, width=50, bg="lightgreen",
fg="black", font=('Helvetica', 20, "bold"),
command=lambda: [GPIO.output(26, GPIO.HIGH), self.after(2000),
GPIO.output(26, GPIO.LOW),
controller.show_frame(StartPage),
self.event_generate('<Motion>', warp=True, x=50, y=50)])
button1.grid(column=0, row=100)

我很感激你帮我做这件事。我刚刚开始学习如何使用python和tkinter,所以我的代码非常复制粘贴,我肯定非常草率。

不要直接在lambda函数中放入太多功能。在你的课上写一个额外的方法:

def clicked(self):
self.button1.config(state="disabled") # disable button
GPIO.output(26, GPIO.HIGH)
self.after(2000, self.proceed) # call method proceed after 2 seconds
def proceed(self):
GPIO.output(26, GPIO.LOW)
# additional stuff

现在,在__init__方法中,使用self.button1 = tk.Button(...将button1作为实例变量。最后,您可以简单地将Button的命令参数设置为新方法:command=self.clicked(不带括号(。

最新更新