tkinter variable for drop down selection empty
Question: I tried to program an app in tkinter that would load random lines from a file
you select from a pull down menu and display the selected line in a text
window.

It seems like the variable "var" in `insert_text` does not return the selected
"option" but rather an "empty" string resulting in a the following error:

> "File not found error" (FileNotFoundError: [Errno2] No such file or
> directory: '').

Please help!

    
    
    #!/usr/bin/env python
    # Python 3
    
    import tkinter
    from tkinter import ttk
    import random
    
    class Application:
    
        def __init__(self, root):
            self.root = root
            self.root.title('Random Stuff')
            ttk.Frame(self.root, width=450, height=185).pack()     
            self.init_widgets()
            var = tkinter.StringVar(root)
            script = var.get()
            choices = ['option1', 'option2', 'option3']
            option = tkinter.OptionMenu(root, var, *choices)
            option.pack(side='right', padx=10, pady=10)              
    
        def init_widgets(self):
            ttk.Button(self.root, command=self.insert_txt, text='Button', width='10').place(x=10, y=10) 
            self.txt = tkinter.Text(self.root, width='45', height='5') 
            self.txt.place(x=10, y=50) 
    
        def insert_txt(self):
            var = tkinter.StringVar(root)
            name = var.get()
            line = random.choice(open(str(name)).readlines())
            self.txt.insert(tkinter.INSERT, line)
    
    if __name__ == '__main__':
        root = tkinter.Tk()
        Application(root)
        root.mainloop()
    


Answer: That's because you're just creating an empty `StringVar` that isn't modified
later, thus returning an empty string.

The OptionMenu takes the `command` parameter that calls the specified method
every time another option is selected. Now, you can call a method like this,
replacing you `insert_txt`:

    
    
    def __init__(self):
        # ...
        self.var = tkinter.StringVar()
        self.options = tkinter.OptionMenu(root, var, *choices, command=self.option_selected)
        # ...    
    
    def option_selected(self, event):
        name = self.var.get()
        # The stuff you already had
    

Additionally, you have to empty the `Text` widget, otherwise the previous text
would stay. I think the `Entry` widget is better for that, too.

