如何将按钮单击分配到tkinter上的变量中

时间:2017-10-11 15:34:37

标签: python python-2.7 tkinter

我想创建一个tkinter窗口,在该窗口中,它会显示文件夹的文件作为下拉菜单和Select按钮,这样当我从上一个列表中选择一个元素时路径将保存到新变量中。显然,我需要给出适当的命令。

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

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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

def do_something():
    #do something

在函数do_something中,您可以创建获取完整路径所需的内容。您也可以将vars传递给命令。

答案 1 :(得分: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()

答案 2 :(得分: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()