如何在单击其按钮时将文件名打印到控制台?

2024-04-18 07:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的示例中,按钮是根据spesific目录中的文件创建的。我在按钮上添加了打印功能。我想做的是,当我单击每个按钮时,每个按钮都应该打印相关文件。但根据下面的代码,当我单击每个按钮时,它们打印的文件名与文件列表的最后一项相同。你能帮我看看这些代码缺少什么吗

from tkinter import *
import os


class Application:
    def __init__(self):
        self.window = Tk()

        self.frame = Frame()
        self.frame.grid(row=0, column=0)

        self.widgets()
        self.mainloop = self.window.mainloop()

    def widgets(self):
        files = self.path_operations()
        for i in range(len(files)):
            button = Button(self.frame, text="button{}".format(i))
            button.grid(row=0, column=i)
            button.configure(command=lambda: print(files[i]))

    @staticmethod
    def path_operations():
        path = "D:\TCK\\Notlar\İş Başvurusu Belgeleri"
        file_list = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path, i))]
        return file_list


a = Application()

Tags: 文件path代码importselfapplicationosdef
1条回答
网友
1楼 · 发布于 2024-04-18 07:24:59

程序需要知道打印什么文件,但是i是共享的,并且会更改。这里有一个技巧:

def widgets(self):
    files = self.path_operations()
    for i in range(len(files)):
        button = Button(self.frame, text="button{}".format(i))
        button.grid(row=0, column=i)
        button.configure(command=self.make_print(files[i]))

@staticmethod
def make_print(file):
    def local_print ():
        print(file)
    return local_print

相关问题 更多 >