首页 > 解决方案 > 两次使用 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!")

标签: pythontkinter

解决方案


推荐阅读