【问题标题】:How to print the file names to the console when clicking their buttons? [duplicate]单击按钮时如何将文件名打印到控制台? [复制]
【发布时间】:2017-11-19 09:54:25
【问题描述】:

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

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

【问题讨论】:

  • 哦,谢谢,我去看看那个页面。

标签: python tkinter


【解决方案1】:

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

【讨论】:

  • 这项技术解决了我的问题。非常感谢。
猜你喜欢
  • 2018-02-23
  • 2021-06-05
  • 2016-07-07
  • 1970-01-01
  • 2021-03-31
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多