首页 > 解决方案 > 如何让 python tkinter 通过输入框验证文件路径?

问题描述

我正在创建一个表单,该表单将包含多行文件路径输入,每个输入框旁边都有一个浏览按钮。用户应该能够将目录路径粘贴到输入表单中,如果没有将背景更改为红色,它将在失去焦点时验证它是现有文件夹。

浏览按钮也可用于输入文件夹路径,当通过浏览按钮选择时,它会将所选路径输入到相应的输入框中。

这是我对python相当新的当前代码,并在tkinter gui上完成了newb,因此试图自学并寻求一些指导

import tkinter as tk
import tkinter.filedialog as fd
from pathlib import Path

root = tk.Tk()

root.geometry("500x500")
root.columnconfigure(0, weight = 1)

def browse_path():
    browse_path = fd.askdirectory()
    path.set(browse_path)
    
def enter_Path():
    entry_path = ent1.get()
    if Path(entry_path).is_dir():
        path.set(entry_path)
        return True
    else:
        ent1.config(bg="red")
        return False
        

label1 = tk.Label(root, text = "This is the Label").grid(row = 0)

path = tk.StringVar(root, value = "Enter the first path here")
ent1 = tk.Entry(root, textvariable = path, validate="focusout", validatecommand="enter_Path")
ent1.grid(padx = 5, pady = 5, row = 2, column = 0, sticky = tk.W + tk.E)

button1 = tk.Button(root, text = "Browse", command = browse_path).grid(row = 2, column = 1)

label2 = tk.Label(root, text = "This is the second label").grid(row = 3)

path2 = tk.StringVar(root, value = "Enter the second path here")
ent2 = tk.Entry(root, textvariable = path2)
ent2.grid(padx = 5, pady = 5, row = 4, column = 0, sticky = tk.W + tk.E)

button2 = tk.Button(root, text = "Browse", command = browse_path).grid(row = 4, column = 1)

root.mainloop()

标签: pythontkinter

解决方案


据我所知,这是你可以做的:

  1. '<FocusOut>'应该使用。这将是如果 GUI 窗口失去焦点。
  2. os.path.isdir(). 我不太熟悉pathlib。我已经导入了os模块并用来os.path.isdir检查它是否是一个文件。

这是一个示例程序:

import tkinter as tk
import tkinter.filedialog as fd
import os

root = tk.Tk()

root.geometry("500x500")
root.columnconfigure(0, weight = 1)

def browse_path():
    browse_path = fd.askdirectory()
    path.set(browse_path)
def browse_path_2():
    browse_path = fd.askdirectory()
    path2.set(browse_path)
    
def enter_Path(event):
    entry_path = path.get()
    entry_path_2=path2.get()
    if not os.path.isdir(entry_path):
        ent1.config(bg="red")
    else:
        ent1.config(bg="white")
    if not os.path.isdir(entry_path_2):
        ent2.config(bg="red")
    else:
        ent2.config(bg="white")
            

label1 = tk.Label(root, text = "This is the Label").grid(row = 0)

path = tk.StringVar(root, value = "Enter the first path here")
ent1 = tk.Entry(root, textvariable = path)
ent1.grid(padx = 5, pady = 5, row = 2, column = 0, sticky = tk.W + tk.E)

button1 = tk.Button(root, text = "Browse", command = browse_path).grid(row = 2, column = 1)

label2 = tk.Label(root, text = "This is the second label").grid(row = 3)

path2 = tk.StringVar(root, value = "Enter the second path here")
ent2 = tk.Entry(root, textvariable = path2)
ent2.grid(padx = 5, pady = 5, row = 4, column = 0, sticky = tk.W + tk.E)

button2 = tk.Button(root, text = "Browse", command = browse_path_2).grid(row = 4, column = 1)
root.bind("<FocusOut>",enter_Path)
root.mainloop()

推荐阅读