python - 将函数绑定到 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)
解决方案
您必须定义一个创建路径的函数,然后必须将该函数绑定到按钮。并确保你在之后没有任何争论
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()
推荐阅读
- android - 房间中的总和和计数 - 别名没有这样的列
- jquery - 我在 laravel 5.3 中使用 twitter 引导程序,并且折叠功能在本地完美运行,但在实时服务器上却没有
- android - AndroidManifest 中的多个 ComponentDiscoveryService --> 合并冲突
- javascript - 在javascript中组合正则表达式
- azure - 具有持久功能的巨大 2 类队列操作计数
- c++ - 高斯模糊永远无法正常工作
- r - R中文件名列表中的矢量模式匹配和矢量替换
- sql - 两个模式之间的 Redshift 提取字符串 (regexp_substr)
- javascript - 修改父prototype.init()函数
- teamcity - 通过 TeamCity/Octopus 部署 ASP.NET 应用程序时,Application Insights 停止工作