2017-10-11 73 views
0

我想創建一個tkinter窗口,在該窗口中將文件夾的文件顯示爲下拉菜單和Select按鈕,這樣當我從上一個選擇元素列出完整的路徑將被保存到一個新的變量中。顯然,我需要給出一個適當的命令。如何將按鈕點擊分配到tkinter上的變量

from Tkinter import * 
import tkFileDialog 
import ttk 
import os 




indir= '/Users/username/results' 


root = Tk() 

b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder. 
b.pack() 
w = Button(master=root, text='Select', command= ?) 
w.pack() 

root.mainloop() 
+0

組件命令通常用於鏈接到一個函數/方法。有'bind()'可用於綁定事件,例如'bind(「

+0

我更新了我的答案,包括將目錄和文件名組合在一起以獲取完整文件路徑的方法。有幾種獲取文件路徑的方法,所以如果你需要更具體的東西讓我知道。 –

回答

1

嘗試是這樣的:

w = Button(master=root, text='Select', command=do_something) 

def do_something(): 
    #do something 

在功能do_something你創建你需要得到完整路徑是什麼。你也可以將變量傳遞給命令。

+0

我該怎麼做?我可以創建一個函數,如: 'def return_full_path(): return indir +? '。但是,我會在問號的位置放置什麼?問號將由鼠標選中,因爲它是下拉列表中的一個元素。 – thanasissdr

+0

我不完全確定你的意思。上面的示例代碼將在您按下按鈕時執行。所以你只需要包含代碼來獲取函數中的路徑。 – GreenSaber

1

我想你在這裏需要的實際上是一個綁定。按鈕不需要。

下面是一個將列出所選目錄中的所有內容的示例,然後當您在組合框中單擊它時,它將打印出其選擇。

更新,添加目錄和文件名稱合併以獲得新的完整路徑:

from Tkinter import * 
import tkFileDialog 
import ttk 
import os 


indir= '/Users/username/results' 
new_full_path = "" 

root = Tk() 

# we use StringVar() to track the currently selected string in the combobox 
current_selected_filepath = StringVar() 
b = ttk.Combobox(master=root, values=current_selected_filepath) 

function used to read the current StringVar of b 
def update_file_path(event=None): 
    global b, new_full_path 
    # combining the directory path with the file name to get full path. 
    # keep in mind if you are going to be changing directories then 
    # you need to use one of FileDialogs methods to update your directory 
    new_full_path = "{}{}".format(indir, b.get()) 
    print(new_full_path) 

# here we set all the values of the combobox with names of the files in the dir of choice 
b['values'] = os.listdir(indir) 
# we now bind the Cobobox Select event to call our print function that reads to StringVar 
b.bind("<<ComboboxSelected>>", update_file_path) 
b.pack() 
# we can also use a button to call the same function to print the StringVar 
Button(root, text="Print selected", command=update_file_path).pack() 

root.mainloop() 
+0

謝謝你的回答。但是,我需要保存結果並不打印它,因爲我需要將其用於其他功能。 – thanasissdr

1

的get() 返回組合框的當前值(https://docs.python.org/3.2/library/tkinter.ttk.html

from Tkinter import * 
import tkFileDialog 
import ttk 
import os 


indir= '/Users/username/results' 

#This function will be invoked with selected combobox value when click on the button 
def func_(data_selected_from_combo): 
    full_path = "{}/{}".format(indir, data_selected_from_combo) 
    print full_path 
    # Use this full path to do further 



root = Tk() 

b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder. 
b.pack() 


w = Button(master=root, text='Select', command=lambda: func_(b.get())) 
w.pack() 

root.mainloop()