首页 > 解决方案 > 好吧,这很奇怪 Python

问题描述

好吧,当我收到此错误时,我只是在使用 TKInter NameError name 'runApps' is not defined

import tkinter as tk
from tkinter import filedialog, Text
import os 

root = tk.Tk()
apps = []
def addApp():

for widget in frame.winfo_children():
    widget.destroy()
filename = filedialog.askopenfilename(initialdir="/", title="Select File",
filetypes=(("executables","*.exe"), ("all files", "*.*")))
apps.append(filename)
print(filename)
for app in apps:
    label = tk.Label(frame, text=app, bg="gray")
    label.pack()


    def runApps():
        for app in apps:
            os.startfile(app)




 canvas = tk.Canvas(root, height=700, width=700, bg="#163542")
 canvas.pack()

 frame = tk.Frame(root, bg="green")
frame.place(relwidth=0.4, relheight=0.4, relx=0.3, rely=0.25)

 openFile = tk.Button(root, text="Open File", padx=10,
 pady=5, fg="white", bg="#163542" ,command=addApp)

 openFile.pack()

 runApps = tk.Button(root, text="Run Apps", padx=10,
 pady=5 , fg="white", bg="#163542" , command = runApps)

 runApps.pack()

 root.mainloop()

好的,如果有人知道如何解决此问题,请发表评论或回答此帖子的此部分仅适用于 ShanyeLoyd 这是您想要的帖子 ShanyeLoyd

标签: pythonpython-3.xtkinter

解决方案


如果您修复代码中的缩进,那么它可以工作。

根据官方文档

逻辑行开头的前导空格(空格和制表符)用于计算行的缩进级别,而缩进级别又用于确定语句的分组。

正确格式化代码:

import tkinter as tk
from tkinter import filedialog
import os

root = tk.Tk()
apps = []


def addApp():
    for widget in frame.winfo_children():
        widget.destroy()
    filename = filedialog.askopenfilename(
        initialdir="/",
        title="Select File",
        filetypes=(("executables", "*.exe"), ("all files", "*.*")),
    )
    apps.append(filename)
    print(filename)
    for app in apps:
        label = tk.Label(frame, text=app, bg="gray")
        label.pack()


def runApps():
    for app in apps:
        os.startfile(app)


canvas = tk.Canvas(root, height=700, width=700, bg="#163542")
canvas.pack()

frame = tk.Frame(root, bg="green")
frame.place(relwidth=0.4, relheight=0.4, relx=0.3, rely=0.25)

openFile = tk.Button(
    root, text="Open File", padx=10, pady=5, fg="white", bg="#163542", command=addApp
)

openFile.pack()

runApps = tk.Button(
    root, text="Run Apps", padx=10, pady=5, fg="white", bg="#163542", command=runApps
)

runApps.pack()

root.mainloop()

图形用户界面:

图形用户界面


推荐阅读