Question

I'm switching over a small app (Python 2.7.3/32 on Win 7/64) to use ttk and I'm having trouble making ttk.Entry work the way tk.Entry does; ttk.Entry isn't updating the displayed entry box when I set its contents:

import Tkinter as tk
import ttk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        part_num = '1234'
        newPNVar = tk.StringVar()
        newPN = ttk.Entry(self, width=13, textvariable=newPNVar)
        newPNVar.set(part_num)
        newPN.pack()
        #newPN.insert(0, part_num)  also didn't work

        print newPNVar.get()


app = SampleApp()
app.mainloop()

If i replace ttk.Entry with tk.Entry and run the example, 1234 shows up in the Entry box, but not if it is a ttk.Entry. How do I get them to behave the same way?

Was it helpful?

Solution

It appears that ttk and tk hold on to the text variable a little differently. It appears that the root cause is that newPNVar is getting garbage collected since you aren't holding on to a reference. This doesn't seem to affect tk.Entry, but does affect ttk.Entry.

The quick fix is to keep a reference to newPNVar (eg: self.newPNVar), which is probably a wise thing regardless of this difference in behavior.

This works for me on Windows:

import Tkinter as tk
import ttk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        part_num = '1234'
        self.newPNVar = tk.StringVar()
        newPN = ttk.Entry(self, width=13, textvariable=self.newPNVar)
        self.newPNVar.set(part_num)
        newPN.pack()
        #newPN.insert(0, part_num)  also didn't work

        print self.newPNVar.get()


app = SampleApp()
app.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top