2017-06-16 70 views
1

在下面的示例中,按鈕是根據特定目錄中的文件創建的。我添加了一個打印功能的按鈕。我想要做的是,當我點擊每個按鈕時,每個按鈕都應該打印相關文件。但根據下面的代碼,當我點擊每個按鈕,他們打印相同的文件名,這是文件列表的最後一項。你能幫我看看這些代碼中缺少什麼嗎?如何在點擊按鈕時將文件名打印到控制檯?

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

哦,謝謝你,我會看看那個頁面。 –

回答

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 
+0

這個技巧解決了我的問題。非常感謝你。 –

相關問題