如何在GUI中从浏览按钮插入选定的文件路径?

2024-10-02 20:32:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我是pythongui创建的新手,我试图从目录中获取.csv文件的文件路径,并将其打印在GUI中的文本框中。我正在使用tkinter库作为GUI,但似乎无法使其正常工作。有谁能帮我解决这个问题吗?在

import tkinter as tk
from tkinter.filedialog import askopenfilename

def browseFile1():
  global infile1
  infile1=askopenfilename()
  txt1.insert(0.0, infile1)

root = tk.Tk()
root.title("CSV Comparison Tool")
Label = tk.Label(root, text="Select CSV files to compare").grid(row = 1, column = 0, columnspan = 30)
browseButton1 = tk.Button(root,text="Browse", command=browseFile1).grid(row = 2, column = 30)
txt1 = tk.Text(root, width = 100, height = 1).grid(row = 2, column = 0, columnspan = 30)
root.mainloop()

错误说明:

^{pr2}$

我先试了一个按钮,然后在下一个按钮上用了它。我用spyder作为工具。在

谢谢!在


Tags: 文件csvimporttkinterguicolumnrootlabel
1条回答
网友
1楼 · 发布于 2024-10-02 20:32:13

你的问题是这些线路:

Label = tk.Label(root, text="Select CSV files to compare").grid(row = 1, column = 0, columnspan = 30)
browseButton1 = tk.Button(root,text="Browse", command=browseFile1).grid(row = 2, column = 30)
txt1 = tk.Text(root, width = 100, height = 1).grid(row = 2, column = 0, columnspan = 30)

小部件上的grid方法与Python中大多数改变对象的方法一样,返回None。而{cd6>{cd6}就是这样。所以当你以后尝试这个:

^{pr2}$

这是在尝试调用None.insert,但显然行不通。Tkinter捕捉到错误,将其打印到终端,并继续运行,就像您的函数从未被调用一样。在

解决办法就是不要那样做。相反,请执行以下操作:

Label = tk.Label(root, text="Select CSV files to compare")
Label.grid(row = 1, column = 0, columnspan = 30)
browseButton1 = tk.Button(root,text="Browse", command=browseFile1)
browseButton1.grid(row = 2, column = 30)
txt1 = tk.Text(root, width = 100, height = 1)
txt1.grid(row = 2, column = 0, columnspan = 30)

现在,您的代码不仅可以工作,它甚至适合于典型的编辑器窗口或堆栈溢出页面。在

相关问题 更多 >