当绘图打开时保持tkinter面板活动

问题描述 投票:1回答:2

以下程序打开一个两列文件,并将一列绘制为另一列的函数。问题是,只要图形窗口打开,tkinter小部件就处于非活动状态。当图形窗口关闭时,它们将再次变为活动状态。我想保持小部件活跃。因此,如果我选择另一个文件,我将不必关闭图形窗口。如何才能做到这一点?我试图使用,例如,top.after(10, openfile),但是,相当期望,该程序提示用户每10毫秒选择一个新文件。

import tkinter as Tk
from tkinter.filedialog import askopenfilename
import matplotlib.pyplot as plt


top = Tk.Tk()

file_name = Tk.StringVar()
f = []
m = []

def openfile():
    global opfi
    opfi = askopenfilename()

def plot():
    global opfi
    del f[:], m[:]
    with open(opfi, 'r') as file:
        for line in range(6000):
            g = file.readline().split('\t')
            field = str(g[0])
            magn = str(g[1])
            f.append(eval(field))
            m.append(eval(magn))

    plt.close()
    plt.plot(f, m, 'b')
    plt.show()


b1 = Tk.Button(top, text='Sample', command=openfile, width=10)
b1.place(relx=0.0, rely=0.0)
b3 = Tk.Button(top, text='Plot', command=plot, width=6)
b3.place(relx=0.4, rely=0.0)

Tk.mainloop()

这是我使用的文件示例:

.983983186936   -0.702925299281
1.00236660232   -0.726670144435
1.02074058078   -0.75169698959
1.03909297815   -0.777209834745
1.05744133036   -0.801262179899
1.0757541608    -0.826426525054
1.09406204943   -0.852315870209
1.11235780038   -0.876239715363
1.13063106929   -0.900676560518
1.14890298837   -0.926342905673
python tkinter
2个回答
0
投票

我做了一些修改,以我喜欢的方式解析文件:

import tkinter as Tk
from tkinter.filedialog import askopenfilename
import matplotlib.pyplot as plt


top = Tk.Tk()

file_name = Tk.StringVar()
f = []
m = []

def openfile():
    global opfi
    opfi = askopenfilename()

def plot():
    global opfi
    del f[:], m[:]
    with open(opfi, 'r') as file:
        g = file.readlines()                # to read unknown number of lines.
    for line_n, line in enumerate(g):       # make '1.00236660232   -0.726670144435\n'
        g[line_n] = line.strip().split()    # [1.00236660232, -0.726670144435]
        f.append(float(g[line_n][0]))       # 1.00236660232
        m.append(float(g[line_n][1]))       # -0.726670144435

    plt.close()
    plt.plot(f, m, 'b')
    plt.show()


b1 = Tk.Button(top, text='Sample', command=openfile, width=10)
b1.place(relx=0.0, rely=0.0)
b3 = Tk.Button(top, text='Plot', command=plot, width=6)
b3.place(relx=0.4, rely=0.0)

top.mainloop()

上面的代码适用于我可以选择另一个样本来绘制gui已经运行时的图形,在:

C:\Users\user>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter as tk
>>> tk.TkVersion
8.6
>>>

0
投票

默认情况下,matplotlib.pyplot.plot()会阻塞,直到您关闭窗口。这会中断mainloop,使您的GUI无响应。

matplotlib文档有一个example如何在Tkinter窗口中嵌入一个图。

© www.soinside.com 2019 - 2024. All rights reserved.