【发布时间】:2020-10-09 07:50:59
【问题描述】:
在我的 tkinter GUI 中,我有两个按钮为不同的参数绘制图形,但是当我单击其中一个按钮时,图形绘制成功并且我没有将 matplotlib 窗口嵌入到任何其他 tkinter 窗口中,我直接调用matplotlib plot ,但是当我没有关闭一个绘制的图形时,如果我单击另一个图形窗口,则会打开其他图形窗口,突然出现错误,python 程序没有响应。因此,将 matplotlib 图嵌入另一个顶层窗口将有助于我们在不将它们嵌入 tkinter 窗口的情况下调用多个图,这是示例代码
from tkinter import *
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("TkAgg")
import mttkinter
import threading
def plottingthefirst():
plt.figure()
parameter1 = [5, 6, 7, 8, 9]
plt.plot(parameter1, marks)
plt.xlabel('parameter1')
plt.ylabel('marks')
plt.show()
def plottingthesecond():
plt.figure()
parameter2 = [1, 2, 3, 4, 5]
plt.plot(parameter2, marks)
plt.xlabel('parameter2')
plt.ylabel('marks')
plt.show()
def func3():
threading.Thread(target=plottingthefirst).start()
def func4():
threading.Thread(target=plottingthesecond).start()
root = Tk(mt_debug=1)
root.geometry('445x788')
global marks
marks = [10, 20, 30, 40, 50]
B1 = Button(root, text="Plot1", command=func3).grid(row=1, column=1)
B2 = Button(root, text="Plot2", command=func4).grid(row=2, column=1)
root.mainloop()
我需要在这里调用线程,因为这不是我使用的确切代码,基本上我在绘制之前进行处理以提取 x 和 y 参数的值,所以如果我删除线程,那么我的主窗口将因此挂起我这里需要线程,所以有什么解决方案可以在不删除线程的情况下同时显示多个图形
【问题讨论】:
-
这部分代码我觉得不错。你能发布完整的代码吗?
-
@AfiJaabb 先生实际上这部分代码只给了我错误,请让我知道您遇到的问题需要理解吗?
-
plottingthefirst()和plottingthesecond()这两个函数可以在主线程中执行吗? -
是的,它们可以,但这会使窗口挂起,因为它也在继续,因此我调用了单独的线程
-
由于
matplotlib不是线程安全的,你最好在主线程中使用它。我也没有看到任何需要在线程中执行。
标签: python python-3.x matplotlib tkinter