使用 Tkinter 的 askopenfilename() 和 matplotlib 在 GUI 中不工作

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

我正在为我的程序创建一个 GUI,我希望第一步是用户选择一个图像,然后显示在 GUI 上。如果我直接将文件路径放入该程序,该程序就可以运行,但是当我使用 askopenfilename() 时,其他用于用户输入的按钮和位置将不再起作用。在 askopenfilename() 之前我有一个完整的工作 GUI。这是给我带来麻烦的代码部分:

from tkinter import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.lines import Line2D
from PIL import Image
from tkinter.filedialog import askopenfilename
from PIL import ImageTk
from tkinter import filedialog

window = Tk()
window.geometry('600x600')

#since I added askopenfilename() I can no longer type in these boxes
e = Entry(window)
e.pack()
ee = Entry(window)
ee.pack()

#path = 'image.png'   #this was working fine
path = filedialog.askopenfilename()
img_arr = plt.imread(path)
img = Image.open(path)

我认为这是 matplotlib 尝试读取它的问题,因为图像打开了,但我无法对它做任何事情。我认为主要问题是我创建了 2 个我无法再输入的对话框。有人遇到过这个问题吗?

python matplotlib user-interface tkinter
1个回答
0
投票

askopenfilename
启动
tk.mainloop
如果它还没有运行,这会弄乱任何创建的
Tk
对象。

解决方案是在

Tk
之后创建
askopenfilename
对象,或者在使用
askopenfilename
启动应用程序的主循环后使用
window.after
,或者将逻辑绑定到屏幕上的按钮。

path = filedialog.askopenfilename()

window = Tk()
# rest of code
window.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.