2013-02-27 173 views
1

我已經編寫了以下代碼來列出給定路徑中的所有目錄/文件,然後將它們寫入按鈕。我如何使用tkinter的事件處理程序,以便每當在窗口小部件中雙擊任何按鈕時調用一個新函數。python tkinter按鈕事件

def display_toplevel(globpath): 
    global row, column 
    dir=globpath 
    dirs = os.listdir(dir) 
    for file in dirs: 
     Button(master, width=8, height=4, text=file).grid(row=row, column=column, padx=10, sticky=W) 
     column = column + 2 
     if column == 10: 
      row = row + 3 
      column = 0 
      column = column + 2 
      break 
+0

你試圖重塑[tkFileDialog(http://tkinter.unpythonic.net/wiki/tkFileDialog) ? Quote:「如果你想打開或保存一個文件或使用filedialog選擇一個目錄,你不需要自己實現它,模塊tkFileDialog只是爲你而已。」 – Junuxx 2013-02-28 10:43:06

回答

3

這適用於單擊;在您創建按鈕的代碼,添加command = # function參數:

Button(master, width=8, height=4, text=file,command=my_funct).grid(row=row, column=column, padx=10, sticky=W) 
# note how the function does not have parentheses (after command=) 

def my_funct(): 
    # code 

參考:Tkinter Button Widget and Parameters

+0

謝謝,我在看綁定的事件並忽略了一些如此微不足道的事情 – bigl 2013-02-27 23:20:21

+0

@bigl:當然,你需要在綁定它之前定義這個函數。 – martineau 2013-02-27 23:36:32