Python:线程和tkinter

m1m5dgzv  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(231)

我尝试在tkinter GUI中连续更新matlibplots,同时能够点击按钮来暂停/继续/停止更新绘图。我尝试使用线程,但它们似乎没有并行执行(例如,数据线程正在执行,但绘图没有得到更新+点击按钮被忽略)。为什么它不起作用?

  1. # Import Modules
  2. import tkinter as tk
  3. from threading import *
  4. import matplotlib.pyplot as plt
  5. from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
  6. from scipy.fft import fft
  7. import numpy as np
  8. import time
  9. import random
  10. # global variables
  11. state = 1 # 0 starting state; 1 streaming; 2 pause; -1 end and save
  12. x = [0]*12
  13. y = [0]*12
  14. # Thread buttons and plots separately
  15. def threading():
  16. state = 1
  17. t_buttons = Thread(target = buttons)
  18. t_plots = Thread(target = plots)
  19. t_data = Thread(target = data)
  20. t_buttons.start()
  21. t_plots.start()
  22. t_data.start()
  23. def hex_to_dec(x, y):
  24. for i in range(0, 12):
  25. for j in range(0, len(y)):
  26. x[i][j] = int(str(x[i][j]), 16)
  27. y[i][j] = int(str(y[i][j]), 16)
  28. def data():
  29. fig1, axs1 = main_plot()
  30. fig2, axs2 = FFT_plot()
  31. # To be replaced with actual Arduino data
  32. while(state!=-1):
  33. for i in range(0, 12):
  34. x[i] = [j for j in range(101)]
  35. y[i] = [random.randint(0, 10) for j in range(-50, 51)]
  36. for i in range(0, 12):
  37. for j in range(0, len(y)):
  38. x[i][j] = int(str(x[i][j]), 16)
  39. y[i][j] = int(str(y[i][j]), 16)
  40. # create buttons
  41. def stream_clicked():
  42. state = 1
  43. print("clicked")
  44. def pause_clicked():
  45. state = 2
  46. print("state")
  47. def finish_clicked():
  48. state = -1
  49. def buttons():
  50. continue_button = tk.Button(window, width = 30, text = "Stream data" ,
  51. fg = "black", bg = '#98FB98', command = stream_clicked)
  52. continue_button.place(x = window.winfo_screenwidth()*0.2, y = 0)
  53. pause_button = tk.Button(window, width = 30, text = "Pause streaming data" ,
  54. fg = "black", bg = '#FFA000', command = pause_clicked)
  55. pause_button.place(x = window.winfo_screenwidth()*0.4, y = 0)
  56. finish_button = tk.Button(window, width = 30, text = "End session and save",
  57. fg = 'black', bg = '#FF4500', command = finish_clicked())
  58. finish_button.place(x = window.winfo_screenwidth()*0.6, y = 0)
  59. def plots():
  60. fig1, axs1 = main_plot()
  61. fig2, axs2 = FFT_plot()
  62. if state==1:
  63. print("update")
  64. for i in range(0, 12):
  65. axs1[i].plot(x[i], y[i], 'blue')
  66. axs1[i].axes.get_yaxis().set_ticks([0], labels = ["channel " + str(i+1)])
  67. axs1[i].grid(True)
  68. axs1[i].margins(x = 0)
  69. fig1.canvas.draw()
  70. fig1.canvas.flush_events()
  71. for i in range(0, 12):
  72. axs1[i].clear()
  73. for i in range(0, 12):
  74. axs2.plot(x[i], fft(y[i]))
  75. plt.title("FFT of all 12 channels", x = 0.5, y = 1)
  76. fig2.canvas.draw()
  77. fig2.canvas.flush_events()
  78. axs2.clear()
  79. def main_plot():
  80. plt.ion()
  81. fig1, axs1 = plt.subplots(12, figsize = (10, 9), sharex = True)
  82. fig1.subplots_adjust(hspace = 0)
  83. # Add fixed values for axis
  84. canvas = FigureCanvasTkAgg(fig1, master = window)
  85. canvas.draw()
  86. canvas.get_tk_widget().pack()
  87. canvas.get_tk_widget().place(x = 0, y = 35)
  88. return fig1, axs1
  89. def update_main_plot(fig1, axs1):
  90. if state==1:
  91. for i in range(0, 12):
  92. axs1[i].plot(x[i], y[i], 'blue')
  93. axs1[i].axes.get_yaxis().set_ticks([0], labels = ["channel " + str(i+1)])
  94. axs1[i].grid(True)
  95. axs1[i].margins(x = 0)
  96. axs1[0].set_title("Plot recordings", x = 0.5, y = 1)
  97. fig1.canvas.draw()
  98. fig1.canvas.flush_events()
  99. for i in range(0, 12):
  100. axs1[i].clear()
  101. def FFT_plot():
  102. # Plot FFT figure
  103. plt.ion()
  104. fig2, axs2 = plt.subplots(1, figsize = (7, 9))
  105. # Add fixed values for axis
  106. canvas = FigureCanvasTkAgg(fig2, master = window)
  107. canvas.draw()
  108. canvas.get_tk_widget().pack()
  109. canvas.get_tk_widget().place(x = window.winfo_screenwidth()*0.55, y = 35)
  110. return fig2, axs2
  111. def update_FFT_plot(fig2, axs2):
  112. # Update FFT plot
  113. for i in range(0, 12):
  114. axs2.plot(x[i], fft(y[i]))
  115. plt.title("FFT", x = 0.5, y = 1)
  116. fig2.canvas.draw()
  117. fig2.canvas.flush_events()
  118. axs2.clear()
  119. # create root window and set its properties
  120. window = tk.Tk()
  121. window.title("Data Displayer")
  122. window.geometry("%dx%d" % (window.winfo_screenwidth(), window.winfo_screenheight()))
  123. window.configure(background = 'white')
  124. threading()
  125. window.mainloop()

有时候,它在没有任何消息的情况下就无法工作,有时候我还会收到“RuntimeError:主线程不在主循环中”

bqjvbblv

bqjvbblv1#

公平地说,代码中的所有函数都很可能导致分段错误,而其他不会导致分段错误的函数则根本无法工作,很难解释错误在哪里。
1.如果要修改全局变量,请将其定义为global
1.通过重复使用window.after方法在主线程中更新GUI。
1.只有从微控制器阅读才应该在单独线程中完成。

  1. Tkinter对象的创建应该在主线程中完成,在其他线程中只允许更新,但它不是线程安全的,因此虽然它可能工作,但有时会导致一些奇怪的行为或错误。
    1.调用matplotlib函数(如ionflush_events)会导致错误,因为这些函数用于matplotlib交互式画布,而不是tkinter画布。
    1.线程化有一个非常坚韧的学习曲线,所以在你尝试使用它们之前,问问自己“我真的需要线程吗”和“有没有办法不使用线程”,因为一旦你开始使用线程,你就不再使用python的“安全代码”,尽管所有的努力,线程在任何任务中都是不安全的,你要让它们安全,老实说,这里不需要线程,除非你从你的微控制器阅读1 GB/s。
    1.不要用数字来表示状态,它不是pythonic,它会让读者感到困惑,而且与使用Enums相比,它没有任何性能优势。
    1.程序是以增量方式构建的,而不是从多个工作片段中复制粘贴,因为当代码的多个部分没有被验证为工作时,很难跟踪错误来自何处。
  1. # Import Modules
  2. import tkinter as tk
  3. from threading import *
  4. import matplotlib.pyplot as plt
  5. from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
  6. from scipy.fft import fft
  7. import numpy as np
  8. import time
  9. import random
  10. from enum import Enum,auto
  11. UPDATE_INTERVAL_MS = 300
  12. class States(Enum):
  13. STREAM = auto()
  14. PAUSE = auto()
  15. SAVE = auto()
  16. START = auto()
  17. # global variables
  18. state = States.START # check States Enum
  19. x = [[0]]*12
  20. y = [[0]]*12
  21. # Thread buttons and plots separately
  22. def threading():
  23. global state
  24. global window
  25. state = States.STREAM
  26. buttons()
  27. plots()
  28. data()
  29. t_grab_data = Thread(target=grab_data_loop,daemon=True)
  30. t_grab_data.start()
  31. # t_buttons = Thread(target=buttons)
  32. # t_plots = Thread(target=plots)
  33. # t_data = Thread(target=data)
  34. #
  35. # t_buttons.start()
  36. # t_plots.start()
  37. # t_data.start()
  38. def hex_to_dec(x, y):
  39. for i in range(0, 12):
  40. for j in range(0, len(y)):
  41. x[i][j] = int(str(x[i][j]), 16)
  42. y[i][j] = int(str(y[i][j]), 16)
  43. def data():
  44. global fig1,axs1,fig2,axs2
  45. fig1, axs1 = main_plot()
  46. fig2, axs2 = FFT_plot()
  47. # To be replaced with actual Arduino data
  48. window.after(UPDATE_INTERVAL_MS,draw_data_loop)
  49. def grab_data_loop():
  50. while state != States.SAVE:
  51. for i in range(0, 12):
  52. x[i] = [j for j in range(101)]
  53. y[i] = [random.randint(0, 10) for j in range(-50, 51)]
  54. for i in range(0, 12):
  55. for j in range(0, len(y)):
  56. x[i][j] = int(str(x[i][j]), 16)
  57. y[i][j] = int(str(y[i][j]), 16)
  58. time.sleep(0.1) # because we are not reading from a microcontroller
  59. def draw_data_loop():
  60. if state == States.STREAM:
  61. update_main_plot(fig1, axs1)
  62. update_FFT_plot(fig2, axs2)
  63. window.after(UPDATE_INTERVAL_MS,draw_data_loop)
  64. # create buttons
  65. def stream_clicked():
  66. global state
  67. state = States.STREAM
  68. print("clicked")
  69. def pause_clicked():
  70. global state
  71. state = States.PAUSE
  72. print("state")
  73. def finish_clicked():
  74. global state
  75. state = States.SAVE
  76. window.destroy()
  77. def buttons():
  78. continue_button = tk.Button(window, width=30, text="Stream data",
  79. fg="black", bg='#98FB98', command=stream_clicked)
  80. continue_button.place(x=window.winfo_screenwidth() * 0.2, y=0)
  81. pause_button = tk.Button(window, width=30, text="Pause streaming data",
  82. fg="black", bg='#FFA000', command=pause_clicked)
  83. pause_button.place(x=window.winfo_screenwidth() * 0.4, y=0)
  84. finish_button = tk.Button(window, width=30, text="End session and save",
  85. fg='black', bg='#FF4500', command=finish_clicked)
  86. finish_button.place(x=window.winfo_screenwidth() * 0.6, y=0)
  87. def plots():
  88. global state
  89. fig1, axs1 = main_plot()
  90. fig2, axs2 = FFT_plot()
  91. if state == States.STREAM:
  92. print("update")
  93. for i in range(0, 12):
  94. axs1[i].plot(x[i], y[i], 'blue')
  95. axs1[i].axes.get_yaxis().set_ticks([0], labels=["channel " + str(i + 1)])
  96. axs1[i].grid(True)
  97. axs1[i].margins(x=0)
  98. # fig1.canvas.draw()
  99. # fig1.canvas.flush_events()
  100. # for i in range(0, 12):
  101. # axs1[i].clear()
  102. for i in range(0, 12):
  103. axs2.plot(x[i], np.abs(fft(y[i])))
  104. plt.title("FFT of all 12 channels", x=0.5, y=1)
  105. # fig2.canvas.draw()
  106. # fig2.canvas.flush_events()
  107. # axs2.clear()
  108. def main_plot():
  109. # plt.ion()
  110. global canvas1
  111. fig1, axs1 = plt.subplots(12, figsize=(10, 9), sharex=True)
  112. fig1.subplots_adjust(hspace=0)
  113. # Add fixed values for axis
  114. canvas1 = FigureCanvasTkAgg(fig1, master=window)
  115. # canvas.draw()
  116. canvas1.get_tk_widget().pack()
  117. canvas1.get_tk_widget().place(x=0, y=35)
  118. return fig1, axs1
  119. def update_main_plot(fig1, axs1):
  120. if state == States.STREAM:
  121. for i in range(0, 12):
  122. axs1[i].clear()
  123. for i in range(0, 12):
  124. axs1[i].plot(x[i], y[i], 'blue')
  125. axs1[i].axes.get_yaxis().set_ticks([0], labels=["channel " + str(i + 1)])
  126. axs1[i].grid(True)
  127. axs1[i].margins(x=0)
  128. axs1[0].set_title("Plot recordings", x=0.5, y=1)
  129. canvas1.draw()
  130. # fig1.canvas.draw()
  131. # fig1.canvas.flush_events()
  132. def FFT_plot():
  133. # Plot FFT figure
  134. # plt.ion()
  135. global canvas2
  136. fig2, axs2 = plt.subplots(1, figsize=(7, 9))
  137. # Add fixed values for axis
  138. canvas2 = FigureCanvasTkAgg(fig2, master=window)
  139. # canvas.draw()
  140. canvas2.get_tk_widget().pack()
  141. canvas2.get_tk_widget().place(x=window.winfo_screenwidth() * 0.55, y=35)
  142. return fig2, axs2
  143. def update_FFT_plot(fig2, axs2):
  144. # Update FFT plot
  145. if state == States.STREAM:
  146. axs2.clear()
  147. for i in range(0, 12):
  148. axs2.plot(x[i], np.abs(fft(y[i])))
  149. plt.title("FFT", x=0.5, y=1)
  150. canvas2.draw()
  151. # fig2.canvas.draw()
  152. # fig2.canvas.flush_events()
  153. # axs2.clear()
  154. # create root window and set its properties
  155. window = tk.Tk()
  156. window.title("Data Displayer")
  157. window.geometry("%dx%d" % (window.winfo_screenwidth(), window.winfo_screenheight()))
  158. window.configure(background='white')
  159. threading()
  160. window.mainloop()
  161. # put saving logic here
展开查看全部

相关问题