Reputation: 33
i found this code online and i wanted to try it out because im trying to figure out how to have my label to change while i type things into my messagebox. I tried the getmethod but i have been struggling with using it. So i found this code and when i tried it i get the error that ttk is undefined but it clearly is.
from Tkinter import *
from ttk import *
def calculate(*args):
try:
value = float(feet.get())
meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
except ValueError:
pass
root = Tk()
root.title("Feet to Meters")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
feet = StringVar()
meters = StringVar()
feet_entry = ttkEntry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))
ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)
ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
feet_entry.focus()
root.bind('<Return>', calculate)
root.mainloop()
Traceback (most recent call last): File "tk8.py", line 15, in mainframe = ttk.Frame(root, padding="3 3 12 12") NameError: name 'ttk' is not defined
Upvotes: 2
Views: 4718
Reputation: 19241
You are looking for the trace_variable
method. Here is a fixed version:
from Tkinter import Tk, StringVar
import ttk
def calculate(*args):
try:
value = float(feet.get())
meters.set('%g' % (0.3048 * value))
except ValueError:
if not feet.get():
meters.set('')
root = Tk()
root.title("Feet to Meters")
feet = StringVar()
feet.trace_variable('w', calculate)
meters = StringVar()
main = ttk.Frame(root)
main.grid(sticky='nsew')
ttk.Label(main, text="Feet:").grid(row=0, sticky='e')
feet_entry = ttk.Entry(main, width=7, textvariable=feet)
feet_entry.grid(row=0, column=1, sticky='ew')
feet_entry.focus()
ttk.Label(main, text="Meters:").grid(row=1, sticky='e')
ttk.Label(main, textvariable=meters).grid(row=1, column=1, sticky='ew')
root.mainloop()
Upvotes: 0
Reputation: 353604
So i found this code and when i tried it i get the error that ttk is undefined but it clearly is.
You're star-importing from the module, though, using from ttk import *
, so the name ttk
doesn't refer to anything. For example, from math import *
would bring sin
, cos
, etc., all into your namespace but the name math
would still be undefined. The code works for me if I switch the imports to
from Tkinter import *
import ttk
and add the missing .
from ttk.Entry
in this line:
feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
Upvotes: 7