如何让python tkinter通过输入框验证文件路径?



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

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

这是我对python相当陌生的当前代码,对tkinter gui完全陌生,所以试图自学并寻找一些指导

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()

根据我的理解,你可以这样做:

应使用
  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()

最新更新