python - 两次使用 tkinter 的文件夹选择对话框
问题描述
在我的代码开始时,我让用户选择一个文件并将其路径存储在一个文本文件中。这是用于该功能的功能:
def choose_folder():
root = tk.Tk()
root.withdraw()
global DIR
DIR = filedialog.askdirectory()
global settings_file # Somehow works without this line despite being declared in main
with open(settings_file, "w") as sf:
sf.write(DIR)
现在,我想让用户更改文件夹。在主循环中,用户每次选择一个选项。选项 4 是更改目录。这是我的代码来改变它:
elif user_input == 4:
open(settings_file, "w").close() # Clear the settings file
choose_folder()
问题是,由于某种原因,文件夹选择对话框不会第二次打开。我已经检查过了,代码到达了 choose_folder() 函数但停止运行filedialog.askdirectory()
(屏幕闪烁一秒钟,这意味着发生了一些事情但没有打开对话框)。是什么导致这种情况发生,我该如何解决?
编辑:这是代码片段(我也略有更改choose_folder()
):
import tkinter as tk
from tkinter import filedialog
import os
#other imports
def prompt_continue() -> bool:
choice = input("Do you want to continue (y/n)? ")[0].lower()
while choice != 'y' and choice != 'n':
choice = input("Invalid Input. ")[0].lower()
return choice == 'y'
def choose_folder():
root = tk.Tk()
root.withdraw()
global DIR
DIR = filedialog.askdirectory()
while not os.path.isdir(DIR):
print("Please choose a folder.")
DIR = filedialog.askdirectory()
while os.listdir(DIR):
print("Please choose an empty folder.")
DIR = filedialog.askdirectory()
with open(settings_file, "w") as sf:
sf.write(DIR)
if __name__ == "__main__":
DIR = ""
settings_file = os.path.expanduser('~/Documents/flagdir.txt')
if os.path.isfile(settings_file): # if settings file exists
if os.stat(settings_file).st_size == 0: # if settings file is empty
choose_folder()
else:
choose_folder()
with open(settings_file, 'r') as file:
DIR = file.read()
user_continue = True
total = 0
while user_continue:
print("Choose option:")
print("[1] Download n random flags")
print("[2] Enter 2 countries and download their mashup")
print("[3] Clear the flags folder")
print("[4] Change the flags folder path")
print("[5] Print the flags folder path")
print("[6] Exit")
user_input = int(input())
while user_input < 1 or user_input > 6:
user_input = int(input("Invalid Input."))
if user_input == 1:
# working code
elif user_input == 2:
# working code
elif user_input == 3:
# working code
elif user_input == 4:
open(settings_file, "w").close()
choose_folder()
elif user_input == 5:
# working code
else:
break
user_continue = prompt_continue()
print("Bye!")
解决方案
推荐阅读
- javascript - 如何使用 SetTimeOut 函数在 javascript 中平滑滚动
- javascript - 从 snap svg 组中的相同位置删除和添加元素
- ios - 如何在 IOS 上使用 FCM 检测卸载?
- mysql - 导入mysql数据库,ubuntu
- python - 如何解决错误“异常:找不到组件类”
我正在 Jupyter Notebook 中使用 rasa_nlu 包启动葡萄牙语聊天机器人,运行代码时收到以下错误消息:
Exception: Failed to find component class for '<spacy.lang.pt.Port
- swift - 如何快速播放目录中保存的本地加密AES128文件?
- excel - VBA Selenium with Chrome - 将文件上传到网页
- docker - k8s 是运行简单应用程序的好主意吗?
- node.js - 需要将 psql 查询转换为 typeorm
- python - ImportError:导入 _openssl 时 DLL 加载失败:%1 不是有效的 Win32 应用程序