以下代码通过单击按钮启动电机。我试过取消注释 R.loop() 但是它接管了整个 GUI 并显示命令提示符和代码运行。代码运行良好,这只是让代码响应按钮点击的问题。
#begin GUI CODE
main = tk.Tk()
main.title('REGENERATOR')
main.geometry('800x800')
#createing global variable for motor run
global is_on
is_on=False
#The following code is to run/stop the motor
def motor_run():
global is_on
running_setup = R.setup()
#running_motor = R.loop()
def on_start():
if is_on:
Button_run.config()
motor_run = True
def on_stop():
if is_on:
Button_stop.config()
motor_run = False
frame5 = LabelFrame(main_canvas, text="Run Program", padx=5, pady=5, font=("Times", 20))
frame5.grid(row=3, column=0)
main_canvas.create_window((0,630), window=frame5, height=150, width= 200, anchor="s")
Button_run=Button(frame5, text="run", command=on_start, bg="white", fg="black", padx=5, pady=5, font=("Times", 16))
Button_run.grid(row="2", column="0")
Button_stop=Button(frame5, text="stop", command=on_stop, bg="white", fg="black", padx=5, pady=5, font=("Times", 16))
Button_stop.grid(row="2", column="1")
# function calls
on_stop()
on_start()
motor_run()
update_value()
update_bat_1()
update_bat_2()
update_gen1()
main_canvas.mainloop()
main.mainloop()
我认为问题可能出在 Button_run.config() 的位置上,似乎只有当电机已经打开/关闭时,程序才会要求自己提供该命令……您可以尝试这样的操作…… .
def on_start():
When Button_run.config() = True
motor_run = True
def on_stop():
When Button_stop.config()
motor_run = False
再次,我不确定这是否与它有关,因为我不熟悉机器人编码,但我认为这可能与它有关。
当你使用这个
import tkinter as tk
。然后将tk.
添加到您添加的每个小部件。
你缺少
Canvas
小部件。
注释掉第50行,
#main_canvas.mainloop()
片段:
import tkinter as tk
main = tk.Tk()
main.title('REGENERATOR')
main.geometry('800x800')
#createing global variable for motor run
global is_on
is_on=False
#The following code is to run/stop the motor
def motor_run():
global is_on
running_setup = R.setup()
#running_motor = R.loop()
def on_start():
if is_on:
Button_run.config()
motor_run = True
def on_stop():
if is_on:
Button_stop.config()
motor_run = False
canvas = tk.Canvas(main, width=600, height=400, bg='white')
canvas.pack(anchor=tk.CENTER, expand=True)
frame5 = tk.LabelFrame(canvas, text="Run Program", padx=5, pady=5, font=("Times", 20))
frame5.grid(row=3, column=0)
canvas.create_window((0,630), window=frame5, height=150, width= 200, anchor="s")
Button_run = tk.Button(frame5, text="run", command=on_start, bg="white", fg="black", padx=5, pady=5, font=("Times", 16))
Button_run.grid(row="2", column="0")
Button_stop = tk.Button(frame5, text="stop", command=on_stop, bg="white", fg="black", padx=5, pady=5, font=("Times", 16))
Button_stop.grid(row="2", column="1")
# function calls
on_stop()
on_start()
motor_run()
update_value()
update_bat_1()
update_bat_2()
update_gen1()
#main_canvas.mainloop()
main.mainloop()
截图。这就是使用
Canvas
的样子: