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

标签 python tkinter

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

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

最佳答案

程序需要以某种方式知道要打印什么文件,但是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

关于python - 单击按钮时如何将文件名打印到控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44592325/

相关文章:

模块中的 python 导入类抛出 ImportError

python - 'DisabledBackend' 对象没有属性 '_get_task_meta_for'

python - 为什么在调整窗口大小时 tkinter.Tk.update() 会阻塞?

Python Tkinter 随机生成颜色?

python - 所有 Tkinter 事件的主列表?

python - OpenCV 错误:错误:(-215)scn == 3 ||函数 cv::cvtColor 中的 scn == 4

python - Pandas:将一行中的 nan 转换为空数组

python - 读取多个 csv 文件,将文件名列表连接到单个 DataFrame 中

python - Tkinter:检查 root 是否已被破坏?

python - ModuleNotFoundError : No module named '_tkinter' on python 3. 8.0 mac OS 10.15.3