Search code examples
pythontkinterttkgetopenfilename

How does one write an HTML-like filename field in Tkinter?


I'm making an auto-generated Tkinter GUI (like an HTML form), and I'm trying to make a filename field like the one HTML uses. Here is my code:

e = ttk.Entry(master)
e.grid(row=ROW, column=1)
b = ttk.Button(master, text="...")
b.grid(row=ROW, column=2, sticky=tkinter.E)

I want it to be so that when the user clicks the ... button, a filename dialog pops up (I know how to do that part), and when the user selects a file, it is reflected in the entry (this is the part I have trouble on). The reason why I have trouble on that part is that E and B constantly change because this is run in a loop, so I think the only way to make this work is to use a row detector, and somehow change the value of the Entry box. How would I do this?

Thanks in advance! If this is by any means unclear, please let me know.


Solution

  • One of the best solutions is to create your own widget as a class. Something like this:

    class MyWidget(self, tkinter.Frame):
        def __init__(self, *args, **kwargs):
            tkinter.Frame.__init__(self, *args, **kwargs)
            self.entry = tkinter.Entry(self)
            self.button = tkinter.Button(self, text="...",
                                         command=self._on_button)
            self.button.pack(side="right")
            self.entry.poack(side="left", fill="both", expand=True)
    
        def _on_button(self):
            s = <call whatever dialog you want...>
            if s != "":
                self.entry.delete(0, "end")
                self.entry.insert(0, s)
    
    ...
    entry = MyWidget(master)
    entry.grid(...)
    ...