python 使用tkinter浏览目录按钮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用tkinter浏览目录按钮相关的知识,希望对你有一定的参考价值。

"""
Example of tkinter code to generate a window with a browse button
to select a directory. Compatible with Python27 and 37
Derived from https://stackoverflow.com/questions/43516019/python-tkinter-browse-folder-button
"""


# Test if Python2, if error import python3 modules
try:
    from Tkinter import *
    import tkFileDialog as filedialog
    
except ImportError:
    from tkinter import *
    from tkinter import filedialog


import os
    
def browse_button():
    # Allow user to select a directory and store it in global var
    # called folder_path (can be then used outside of the function)
    global folder_path
    # The title will appear in the pop up window when selecting directory
    filename = filedialog.askdirectory(initialdir=os.getcwd(), title='Please select input directory')
    folder_path.set(filename)
    print(filename)

# create root
root = Tk()

# Create Tkinter variable
folder_path = StringVar()

# Display first the lbl0, then the button2, then the lbl1

# Create text before the button
lbl0 = Label(master=root, text="Choose input directory")
lbl0.grid(row=0, column=0)

# Create a place for the name of the directory once it will be assigned 
# with the function browse_button
lbl1 = Label(master=root,textvariable=folder_path)
lbl1.grid(row=0, column=2)

# Create button to search for directory and call browse_button command
button2 = Button(text="Browse", command=browse_button)
button2.grid(row=0, column=1)

# Launch main loop
mainloop()

以上是关于python 使用tkinter浏览目录按钮的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Python 中使用 tkinter 选择目录并存储位置

python tkinter 右键菜单出错,怎么改?

python tkinter动态追加按钮等控件可能遇到的问题

Python使用matplotlib可视化绘制并通过Tkinter生成按钮将可视化结果导出为pdf文件

tkinter 询问目录()

如何使用 Tkinter 按钮运行 Python 脚本?