首页 > 解决方案 > 将函数绑定到 Tkinter 中的按钮以创建文件夹结构

问题描述

尝试使用 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)

标签: pythontkinterbuttonbinding

解决方案


您必须定义一个创建路径的函数,然后必须将该函数绑定到按钮。并确保你在之后没有任何争论

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

推荐阅读