Tkinter Filedialog.askopenfilename迭代

时间:2018-11-14 12:54:28

标签: python tkinter iteration openfiledialog

我正在开发程序来加载文件并使用这些加载的文件执行一些计算。

为此,我编写了一个简单的迭代代码来加载tkinter变量。窗口,标签,输入和按钮位置已经完成。到目前为止,我拥有的代码是:

 W/System.err: org.json.JSONException: Value Exception of type java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:112)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:163)
        at org.json.JSONObject.<init>(JSONObject.java:176)
        at com.LoginActivity$SendPostRequest.onPostExecute(LoginActivity.java:488)
        at com.LoginActivity$SendPostRequest.onPostExecute(LoginActivity.java:417)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.access$600(AsyncTask.java:180)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

我的问题在于点击按钮。本来可以在单击过程中运行askopenfilename,获取文件路径并显示在输入框上,但是所有按钮都将其定向到最后创建的输入框。

有人可以帮助我解决这个问题吗?

非常感谢!

2 个答案:

答案 0 :(得分:1)

facet_wrap进行营救。一个人需要知道正确的Button-Entry对来更新。因此,在按下按钮时传递相应索引的值。

Lambda

enter image description here

答案 1 :(得分:0)

我认为您应该通过使用列表存储输入字段来简化一些事情。 为此,我认为最好为每组小部件添加框架并使用range的索引来获得所需的内容。

我对您的代码做了一些修改,以使其更易于使用列表索引,并添加了一个按钮,该按钮将在每个输入字段上打印出每个选定的路径,以显示这些值是可访问的。

import tkinter as tk
from tkinter import ttk, filedialog

LARGE_FONT = ("Arial", 12)
MEDIUM_FONT = ("Arial", 11)
REGULAR_FONT = ("Arial", 10)

text_z = ["Select file 1", "Select the file 2", "Select file 3", "Select file 4"]

window = tk.Tk()

def click(x): 
    z = tk.filedialog.askopenfilename(initialdir="/", title="Select file", filetypes=(("Excel file", "*.xlsx"), ("All files", "*.*")))
    a[x].insert(tk.END, z)

ttk.Label(window, text="file load", font=LARGE_FONT, background="white").grid(row=1, column=0, padx=20, pady=10, sticky="w")

a=[]

for i in range(len(text_z)): 
    frame = tk.Frame(window)
    frame.grid(row=i+2, column=0, sticky="nsew")
    ttk.Label(frame, text=text_z[i], background="white").grid(row=0, column=0, columnspan=3, padx=10, pady=2, sticky="w")
    a.append(ttk.Entry(frame, width=60, background="gray"))
    a[i].grid(row=1, column=0, columnspan=3, padx=10, sticky="ew")
    ttk.Button(frame, text="Search", width=10, command=lambda x=i: click(x)).grid(row=1, column=3, padx=5, sticky="w")

def pring_current_paths():
    for ndex, entry in enumerate(a):
        print("Entry {}: ".format(ndex, entry.get()))

tk.Button(window, text="Print gurrent paths!", command=pring_current_paths).grid()

window.mainloop()