首页 > 解决方案 > 获取目录后更新文件路径

问题描述

我是 python 新手,正在尝试创建一个需要输入和输出目录的 GUI。My goal is to have a textbox new to a browse button and when the directory is selected the textbox will display the directory path. 但是,我不确定如何更改在函数中单击按钮时显示的文本。

from tkinter import *
from tkinter import filedialog
import tkinter as tk

class App:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)
        T_out= tk.Text(root, height=1, width=50)
        T_out.pack(side=TOP)
        self.hi_there= Button(frame, text="Browse", command=self.getoutputdir)
        self.hi_there.pack(side=LEFT)
        T_in = tk.Text(root, height=1, width=50)
        T_in.pack(side=LEFT)
        self.input_1= Button(frame, text="Browse", command=self.getinputdir)
        self.input_1.pack(side=LEFT)

    def getoutputdir(self):
        global outputdir
        outputdir = filedialog.askdirectory(parent=root,initialdir="/",title='Please select the output directory')
        T_out.text(tk.END,outputdir)
    def getinputdir(self):
        global inputdir
        inputdir = filedialog.askdirectory(parent=root,initialdir="/",title='Please select the input directory')
        T_in.text(tk.END,inputdir)
root = Tk()
root.title('GUI for CZI')
app = App(root)

root.mainloop()

标签: pythontkinter

解决方案


有两个主要问题阻止了它的工作。首先是在getinputdirandgetoutputdir函数中。您需要确保对T_in和的引用T_out可用。您可以通过将它们存储在 App 对象中来做到这一点。

第二个主要问题是.text不是一个有效的方法。您可以使用.delete清除它然后.insert插入新目录。

from tkinter import *
from tkinter import filedialog
import tkinter as tk

class App:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)
        self.T_out= tk.Text(root, height=1, width=50)
        self.T_out.pack(side=TOP)
        self.hi_there= Button(frame, text="Browse", command=self.getoutputdir)
        self.hi_there.pack(side=LEFT)
        self.T_in = tk.Text(root, height=1, width=50)
        self.T_in.pack(side=LEFT)
        self.input_1= Button(frame, text="Browse", command=self.getinputdir)
        self.input_1.pack(side=LEFT)

    def getoutputdir(self):
        global outputdir
        outputdir = filedialog.askdirectory(parent=root,initialdir="/",title='Please select the output directory')
        self.T_out.delete(1.0, tk.END)
        self.T_out.insert(tk.END, outputdir)
    def getinputdir(self):
        global inputdir
        inputdir = filedialog.askdirectory(parent=root,initialdir="/",title='Please select the input directory')
        self.T_in.delete(1.0, tk.END)
        self.T_in.insert(tk.END, inputdir)
root = Tk()
root.title('GUI for CZI')
app = App(root)

root.mainloop()

推荐阅读