python Tkinter -带按钮的循环开始/停止-穿线选项

2nc8po8w  于 2023-09-29  发布在  Python
关注(0)|答案(1)|浏览(129)

我有一个问题,终止的while循环,这是通过线程选项启动。
stop变量的值为True和False。我应该通过线程启动停止选项吗?
完整的程序开始,一个循环开始,每秒打印一次TEST,点击STOP按钮,我什么也得不到!
我甚至认为我的停止是禁用时,循环正在进行中!

  1. import tkinter as tk
  2. import threading
  3. import time
  4. class App(tk.Tk):
  5. def __init__(self):
  6. super().__init__()
  7. global stop
  8. stop = False
  9. # If the STOP button is pressed then terminate the loop
  10. def button_stop_command():
  11. global stop
  12. stop = True
  13. # Start loop
  14. def button_start_command():
  15. global stop
  16. stop = False
  17. while stop == False:
  18. print("TEST")
  19. time.sleep(1)
  20. # Button starter with thread
  21. def button_starter():
  22. t = threading.Thread(target=button_start_command)
  23. t.start()
  24. # self windows size
  25. window_width = 1024
  26. window_height = 600
  27. # get the screen dimension
  28. screen_width = self.winfo_screenwidth()
  29. screen_height = self.winfo_screenheight()
  30. # find the center point
  31. center_x = int(screen_width/2 - window_width / 2)
  32. center_y = int(screen_height/2 - window_height / 2)
  33. # set the position of the window to the center of the screen
  34. self.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
  35. # Resize main window xy, on/off, 0 or 1 .
  36. self.resizable(0, 0)
  37. # Main window on top of stack.
  38. self.attributes('-topmost', 1)
  39. # Windows transparency.
  40. self.attributes('-alpha', 1)
  41. # Button START
  42. # self.button = tk.Button(self, text='START', width = 20, height = 10, command = self.button_clicked)
  43. self.button = tk.Button(self, text='START', width = 20, height = 10, command = button_start_command)
  44. self.button.place(x = 600, y = 350)
  45. # Button STOP
  46. # self.button = tk.Button(self, text='START', width = 20, height = 10, command = self.button_clicked)
  47. self.button_stop = tk.Button(self, text='STOP', width = 20, height = 10, command = button_stop_command)
  48. self.button_stop.place(x = 800, y = 350)
  49. if __name__ == "__main__":
  50. app = App()
  51. app.mainloop()

使用STOP按钮停止循环!

mfuanj7w

mfuanj7w1#

回答你的问题“我应该通过线程启动停止选项吗?“是的,我想你应该这样做,你已经快做完了!“!”只需要将“command = button_start_command”更改为“command = button_starter”,就可以在我的环境中工作!!

相关问题