2017-10-11 77 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()