将函数绑定到 Tkinter 中的按钮以创建文件夹结构

Binding functions to buttons in Tkinter to create a folder structure

尝试创建一个带有 1 个按钮的 GUI,按下该按钮将创建一个文件夹结构。 我有两个程序可以独立工作,但不确定如何在 Tkinter 中将其绑定到 运行 并在按下按钮后创建文件夹结构?

`from tkinter import *

root = Tk()

def printName(event):
    print("config folder created")

button_1 = Button(root, text="config folder")
button_1.bind("<Button-1>", printName)
button_1.pack()

root.mainloop()`

    import os

#Create a folder structure
project = "01"
app = "app"
mw = "me"
a = "a"
b = "b"
c = "c"
d = "d"
e = "e"
f = "f"

root = "C:\Users\user_name\Documents"
path = f"{root}/{project}/{app}/{mw}/{a}/{b}/{c}/{d}/{e}/{f}".lower().replace(" ","")
print(path)

#If path exists don't create
if not os.path.exists(path):
    os.makedirs(path)

您必须定义一个函数来创建您的路径,然后您必须将该函数绑定到按钮。 并确保在

之后没有任何参数
root.mainloop()

因为这就像一个无穷大的 while 循环,之后什么都不会执行。 还要确保在将函数绑定到按钮之前定义您的函数,否则您无法将它绑定到按钮,因为它尚未定义。

import tkinter as tk
import os

root = tk.Tk()

def printName(event):
    print("config folder created")

def create_folders(event):
    #Create a folder structure
    project = "01"
    app = "app"
    mw = "me"
    a = "a"
    b = "b"
    c = "c"
    d = "d"
    e = "e"
    f = "f"

    root = "C:\Users\user_name\Documents"
    path = f"{root}/{project}/{app}/{mw}/{a}/{b}/{c}/{d}/{e}/{f}".lower().replace(" ","")
    print(path)

    #If path exists don't create
    if not os.path.exists(path):
        os.makedirs(path)

button_1 = tk.Button(root, text="config folder")
button_1.bind("<Button-1>", printName)
button_1.pack()
button_1.bind(create_folders)

root.mainloop()

root.mainloop() 之后的代码将在根 window 关闭或销毁后才会执行。

只需将root.mainloop()之后的代码移动到printName()函数中:

from tkinter import *
import os

root = Tk()

def printName(event):
    #Create a folder structure
    project = "01"
    app = "app"
    mw = "me"
    a = "a"
    b = "b"
    c = "c"
    d = "d"
    e = "e"
    f = "f"

    root = "C:\Users\user_name\Documents"
    path = f"{root}/{project}/{app}/{mw}/{a}/{b}/{c}/{d}/{e}/{f}".lower().replace(" ","")
    print(path)

    #If path exists don't create
    if not os.path.exists(path):
        os.makedirs(path)
        print("config folder created")

button_1 = Button(root, text="config folder")
button_1.bind("<Button-1>", printName)
button_1.pack()

root.mainloop()