The code won't even display the root, let alone the menus. Even when the conversion works, nothing else does, so what do I do?

from Tkinter import *
root = Tk()
def hello():
    print "Hello!"
def metres_to_centimetres(metre,cm):
    metre = input("Put in a distance in metres: ")
    cm = metre*100
    print "Distance in Centimetres = ",cm
 
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Hello", command=hello)
filemenu.add_command(label="M to Cm", command=metres_to_centimetres(metre,cm))
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
mainloop()

Where have I gone wrong? I was altering code from a tutorial.

Recommended Answers

All 6 Replies

To update the problem, the "def metres_to_centimetres" runs first, then the gui displays, then the "M to cm" button does nothing while "hello" works perfectly.

Several problems with your program, I corrected some of them:

from Tkinter import *

root = Tk()

def hello():
    print "Hello!"

# removed unneeded arguments (metre,cm)
def metres_to_centimetres():
    metre = input("Put in a distance in metres: ")
    cm = metre*100
    print "Distance in Centimetres = ",cm
 
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Hello", command=hello)

# command accepts a function object but not a function call
# to pass any arguments you have to wrap the object in lambda
#filemenu.add_command(label="M to Cm", command=metres_to_centimetres(metre,cm))  # gives error
# actually you don't need to pass any arguments
filemenu.add_command(label="M to Cm", command=metres_to_centimetres)

filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
mainloop()

Now the major problem is that you are mixing console only functions like print and input with a GUI environment. In a GUI program you use widget Label for prompts and results, and widget Entry for data entry/input or display. Actions are generally done with a button click. Here is an example:

# example of a labeled data entry, a button and a result label
# use grid to position widgets, also set cursor to focus on entry
# a rather generic Tkinter GUI template for calculations

from Tkinter import *

def calculate():
    try:
        # get the enter1 value
        # use float() for either float or integer entry
        num1 = float(enter1.get())
        # do the calculation
        result = num1 * 100
        # display the result string
        # use str() to convert numbers to string for concatination with +
        label2.config(text=str(num1) + 'meters = ' + str(result) + 'cm')
    except ValueError:
        label2.config(text='Enter a numeric value!')

root = Tk()

# data entry with a prompt label
label1 = Label(root, text='Enter distance in meters:')
label1.grid(row=0, column=0)
enter1 = Entry(root, bg='yellow')
enter1.grid(row=1, column=0)

# do the calculation by clicking the button
btn1 = Button(root, text='Calculate Result', command=calculate)
btn1.grid(row=2, column=0)

# display the result in this label
label2 = Label(root, bg='green')
label2.grid(row=3, column=0)

# start cursor in enter1
enter1.focus()

root.mainloop()

GUI/Windows programming is a mildly different world. I would get my Python basics under my belt before getting too deep into GUI.

It says There is no attribute Tk, even though the command is right where you put it. Here's my program for another update:

from Tkinter import *
def calculate():
    try:
        metre = float(enter1.get())
        result = metre * 100
        label2 = Label(calculate, bg="blue")
        label2.config(text=str(metre)+ 'meters = ' + str(result)+'cm')
    except ValueError:
        label2.config(text="Enter a numeric value!")
    
root = Tk()
                      
label1 = Label(root, text="Enter distance in metres: ")
label1.grid(row=0, column=0)
enter1 = Entry(root, bg="Yellow")
enter1.grid(row=1, column=0)
btnl = Button(root, text="Calculate Result", command=calculate)
btnl.grid(row=2, column=0)
mainloop()

Where is my mistake this time?

See my comments in the code ...

from Tkinter import *
def calculate():
    try:
        metre = float(enter1.get())
        result = metre * 100
        #label2 = Label(calculate, bg="blue")  # error here
        label2 = Label(root, bg="blue")        # black text on blue is hard to see!
        label2.grid(row=3, column=0)           # this was missing
        label2.config(text=str(metre)+ 'meters = ' + str(result)+'cm')
    except ValueError:
        label2.config(text="Enter a numeric value!")
    
root = Tk()
                      
label1 = Label(root, text="Enter distance in metres: ")
label1.grid(row=0, column=0)
enter1 = Entry(root, bg="Yellow")
enter1.grid(row=1, column=0)
btnl = Button(root, text="Calculate Result", command=calculate)
btnl.grid(row=2, column=0)
mainloop()

You can replace console based things like print and input with popup dialog boxes, then you can use the menu you constructed ...

from Tkinter import *
from tkMessageBox   import showinfo
from tkSimpleDialog import askfloat

root = Tk()

def hello():
    # print "Hello!"  # console only
    showinfo(None, "Hello!")
    
def meters_to_centimeters():
    # meter = input("Put in a distance in meters: ")  # console only
    meter = askfloat(None, "Put in a distance in meters:")
    cm = meter * 100
    # print "Distance in Centimeters = ",cm
    showinfo(None, "Distance in Centimeters = " + str(cm))
 
menubar = Menu(root)
filemenu = Menu(menubar,  tearoff=0)
filemenu.add_command(label="Hello", command=hello)
filemenu.add_command(label="M to Cm", command=meters_to_centimeters)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()

Sorry, had to use meter instead of metre, a habit of mine.

Thanks everyone. I'll look out for the submissions Ene Uran submits into the Beginner programs thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.