首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:线程和tkinter

Python:线程和tkinter
EN

Stack Overflow用户
提问于 2022-10-29 10:53:22
回答 1查看 72关注 0票数 0

我试图在tkinter中不断更新matlibplots,同时能够单击按钮来暂停/继续/停止更新绘图。我尝试过使用线程,但它们似乎并不是并行执行的(例如,正在执行数据线程,但是没有更新图形,并忽略了单击按钮)。为什么不动呢?

代码语言:javascript
复制
# Import Modules
import tkinter as tk
from threading import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from scipy.fft import fft
import numpy as np
import time
import random

# global variables
state = 1             # 0 starting state; 1 streaming; 2 pause; -1 end and save
x = [0]*12
y = [0]*12

# Thread buttons and plots separately
def threading():
    state = 1
    
    t_buttons = Thread(target = buttons)
    t_plots = Thread(target = plots)
    t_data = Thread(target = data)
    
    t_buttons.start()
    t_plots.start()
    t_data.start()
    
def hex_to_dec(x, y):
    for i in range(0, 12):
        for j in range(0, len(y)):
            x[i][j] = int(str(x[i][j]), 16)
            y[i][j] = int(str(y[i][j]), 16)
    
def data():
    fig1, axs1 = main_plot()
    fig2, axs2 = FFT_plot()
    # To be replaced with actual Arduino data
    while(state!=-1):
        for i in range(0, 12):
            x[i] = [j for j in range(101)]
            y[i] = [random.randint(0, 10) for j in range(-50, 51)]
        for i in range(0, 12):
            for j in range(0, len(y)):
                x[i][j] = int(str(x[i][j]), 16)
                y[i][j] = int(str(y[i][j]), 16)

# create buttons
def stream_clicked():
    state = 1
    print("clicked")
    
def pause_clicked():
    state = 2
    print("state")
    
def finish_clicked():
    state = -1
    
    
def buttons():
    continue_button = tk.Button(window, width = 30, text = "Stream data" , 
                              fg = "black", bg = '#98FB98', command = stream_clicked)
    continue_button.place(x = window.winfo_screenwidth()*0.2, y = 0)

    pause_button = tk.Button(window, width = 30, text = "Pause streaming data" , 
                             fg = "black", bg = '#FFA000', command = pause_clicked)
    pause_button.place(x = window.winfo_screenwidth()*0.4, y = 0)

    finish_button = tk.Button(window, width = 30, text = "End session and save", 
                              fg = 'black', bg = '#FF4500', command = finish_clicked())
    finish_button.place(x = window.winfo_screenwidth()*0.6, y = 0)
    
def plots():
    fig1, axs1 = main_plot()
    fig2, axs2 = FFT_plot()
    
    if state==1:
        print("update")
        for i in range(0, 12):
            axs1[i].plot(x[i], y[i], 'blue')
            axs1[i].axes.get_yaxis().set_ticks([0], labels = ["channel  " + str(i+1)])
            axs1[i].grid(True)
            axs1[i].margins(x = 0)
        
        fig1.canvas.draw()
        fig1.canvas.flush_events()
        for i in range(0, 12):
            axs1[i].clear()
        for i in range(0, 12):
            axs2.plot(x[i], fft(y[i]))
        plt.title("FFT of all 12 channels", x = 0.5, y = 1)
        
        fig2.canvas.draw()
        fig2.canvas.flush_events()
        axs2.clear()

def main_plot():
    plt.ion()
    
    fig1, axs1 = plt.subplots(12, figsize = (10, 9), sharex = True)
    fig1.subplots_adjust(hspace = 0)
    # Add fixed values for axis
    
    canvas = FigureCanvasTkAgg(fig1, master = window)  
    canvas.draw()
    canvas.get_tk_widget().pack()
    canvas.get_tk_widget().place(x = 0, y = 35)
    
    return fig1, axs1
    
def update_main_plot(fig1, axs1):
    if state==1:
        for i in range(0, 12):
            axs1[i].plot(x[i], y[i], 'blue')
            axs1[i].axes.get_yaxis().set_ticks([0], labels = ["channel  " + str(i+1)])
            axs1[i].grid(True)
            axs1[i].margins(x = 0)
        axs1[0].set_title("Plot recordings", x = 0.5, y = 1)
        
        fig1.canvas.draw()
        fig1.canvas.flush_events()
        for i in range(0, 12):
            axs1[i].clear()
    
    
def FFT_plot():
    # Plot FFT figure 
    plt.ion()
    
    fig2, axs2 = plt.subplots(1, figsize = (7, 9))
    # Add fixed values for axis
    
    canvas = FigureCanvasTkAgg(fig2, master = window)  
    canvas.draw()
    canvas.get_tk_widget().pack()
    canvas.get_tk_widget().place(x = window.winfo_screenwidth()*0.55, y = 35)
    
    return fig2, axs2


def update_FFT_plot(fig2, axs2):
    # Update FFT plot
    for i in range(0, 12):
        axs2.plot(x[i], fft(y[i]))
    plt.title("FFT", x = 0.5, y = 1)
    
    fig2.canvas.draw()
    fig2.canvas.flush_events()
    axs2.clear()

# create root window and set its properties
window = tk.Tk()
window.title("Data Displayer")
window.geometry("%dx%d" % (window.winfo_screenwidth(), window.winfo_screenheight()))
window.configure(background = 'white')

threading()

window.mainloop()

*有时没有任何消息就无法工作,有时我还得到"RuntimeError:主线程不在主循环“*

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-29 14:51:36

公平地说,代码中的所有函数都很可能导致分段错误,而其他不导致分段错误的函数根本不起作用,很难解释出哪里出了问题。

如果要使用repeatedly.

  • only方法修改主线程中的

  • 更新GUI,则
  1. 将全局变量定义为global,从微控制器读取的应该在单独的Tkinter对象中完成,只允许在其他线程中进行更新,但它并不是线程安全的,所以虽然它可能会导致一些奇怪的行为或错误,比如ionflush_events会导致错误,因为这些都是用于matplotlib交互画布的,对于tkinter来说,canvas.
    1. threading的学习曲线不是很难,所以在尝试使用线程之前,问问自己“我真的需要线程吗?”和“有没有办法不使用线程”,因为一旦开始使用线程,您就不再使用python的“安全代码”了,尽管付出了种种努力,线程还是不安全地用于任何任务,这取决于您如何确保它们的安全,并且诚实地说,这里不需要线程,除非您从状态的microcontroller.
    2. don't使用数字中读取了1GB/s,这不是仿生的,它使读取器感到困惑,而且它没有使用Enums.
    3. programs的性能好处,而不是从多个工作代码段复制粘贴,因为当代码的多个部分不工作时,很难跟踪错误的来源。

代码语言:javascript
复制
# Import Modules
import tkinter as tk
from threading import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from scipy.fft import fft
import numpy as np
import time
import random
from enum import Enum,auto

UPDATE_INTERVAL_MS = 300

class States(Enum):
    STREAM = auto()
    PAUSE = auto()
    SAVE = auto()
    START = auto()


# global variables
state = States.START  # check States Enum
x = [[0]]*12
y = [[0]]*12


# Thread buttons and plots separately
def threading():
    global state
    global window
    state = States.STREAM

    buttons()
    plots()
    data()
    t_grab_data = Thread(target=grab_data_loop,daemon=True)
    t_grab_data.start()
    # t_buttons = Thread(target=buttons)
    # t_plots = Thread(target=plots)
    # t_data = Thread(target=data)
    #
    # t_buttons.start()
    # t_plots.start()
    # t_data.start()


def hex_to_dec(x, y):
    for i in range(0, 12):
        for j in range(0, len(y)):
            x[i][j] = int(str(x[i][j]), 16)
            y[i][j] = int(str(y[i][j]), 16)


def data():
    global fig1,axs1,fig2,axs2
    fig1, axs1 = main_plot()
    fig2, axs2 = FFT_plot()
    # To be replaced with actual Arduino data
    window.after(UPDATE_INTERVAL_MS,draw_data_loop)


def grab_data_loop():
    while state != States.SAVE:
        for i in range(0, 12):
            x[i] = [j for j in range(101)]
            y[i] = [random.randint(0, 10) for j in range(-50, 51)]
        for i in range(0, 12):
            for j in range(0, len(y)):
                x[i][j] = int(str(x[i][j]), 16)
                y[i][j] = int(str(y[i][j]), 16)
        time.sleep(0.1)  # because we are not reading from a microcontroller

def draw_data_loop():
    if state == States.STREAM:
        update_main_plot(fig1, axs1)
        update_FFT_plot(fig2, axs2)
    window.after(UPDATE_INTERVAL_MS,draw_data_loop)


# create buttons
def stream_clicked():
    global state
    state = States.STREAM
    print("clicked")


def pause_clicked():
    global state
    state = States.PAUSE
    print("state")


def finish_clicked():
    global state
    state = States.SAVE
    window.destroy()


def buttons():
    continue_button = tk.Button(window, width=30, text="Stream data",
                                fg="black", bg='#98FB98', command=stream_clicked)
    continue_button.place(x=window.winfo_screenwidth() * 0.2, y=0)

    pause_button = tk.Button(window, width=30, text="Pause streaming data",
                             fg="black", bg='#FFA000', command=pause_clicked)
    pause_button.place(x=window.winfo_screenwidth() * 0.4, y=0)

    finish_button = tk.Button(window, width=30, text="End session and save",
                              fg='black', bg='#FF4500', command=finish_clicked)
    finish_button.place(x=window.winfo_screenwidth() * 0.6, y=0)


def plots():
    global state
    fig1, axs1 = main_plot()
    fig2, axs2 = FFT_plot()

    if state == States.STREAM:
        print("update")
        for i in range(0, 12):
            axs1[i].plot(x[i], y[i], 'blue')
            axs1[i].axes.get_yaxis().set_ticks([0], labels=["channel  " + str(i + 1)])
            axs1[i].grid(True)
            axs1[i].margins(x=0)

        # fig1.canvas.draw()
        # fig1.canvas.flush_events()
        # for i in range(0, 12):
        #     axs1[i].clear()
        for i in range(0, 12):
            axs2.plot(x[i], np.abs(fft(y[i])))
        plt.title("FFT of all 12 channels", x=0.5, y=1)

        # fig2.canvas.draw()
        # fig2.canvas.flush_events()
        # axs2.clear()


def main_plot():
    # plt.ion()
    global canvas1
    fig1, axs1 = plt.subplots(12, figsize=(10, 9), sharex=True)
    fig1.subplots_adjust(hspace=0)
    # Add fixed values for axis

    canvas1 = FigureCanvasTkAgg(fig1, master=window)
    # canvas.draw()
    canvas1.get_tk_widget().pack()
    canvas1.get_tk_widget().place(x=0, y=35)

    return fig1, axs1


def update_main_plot(fig1, axs1):
    if state == States.STREAM:
        for i in range(0, 12):
            axs1[i].clear()
        for i in range(0, 12):
            axs1[i].plot(x[i], y[i], 'blue')
            axs1[i].axes.get_yaxis().set_ticks([0], labels=["channel  " + str(i + 1)])
            axs1[i].grid(True)
            axs1[i].margins(x=0)
        axs1[0].set_title("Plot recordings", x=0.5, y=1)
        canvas1.draw()
        # fig1.canvas.draw()
        # fig1.canvas.flush_events()



def FFT_plot():
    # Plot FFT figure
    # plt.ion()
    global canvas2
    fig2, axs2 = plt.subplots(1, figsize=(7, 9))
    # Add fixed values for axis

    canvas2 = FigureCanvasTkAgg(fig2, master=window)
    # canvas.draw()
    canvas2.get_tk_widget().pack()
    canvas2.get_tk_widget().place(x=window.winfo_screenwidth() * 0.55, y=35)

    return fig2, axs2


def update_FFT_plot(fig2, axs2):
    # Update FFT plot
    if state == States.STREAM:
        axs2.clear()
        for i in range(0, 12):
            axs2.plot(x[i], np.abs(fft(y[i])))
        plt.title("FFT", x=0.5, y=1)
        canvas2.draw()
    # fig2.canvas.draw()
    # fig2.canvas.flush_events()
    # axs2.clear()


# create root window and set its properties
window = tk.Tk()
window.title("Data Displayer")
window.geometry("%dx%d" % (window.winfo_screenwidth(), window.winfo_screenheight()))
window.configure(background='white')

threading()

window.mainloop()

# put saving logic here
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74244687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档