Home > Net >  Why is the button not working on my tkinter temp converter?
Why is the button not working on my tkinter temp converter?

Time:06-17

I need to make a temperature converter for a class through tkinter. All the labels and buttons come up but my button does not do anything when clicked. I have tried multiple different definitions of the command with no luck.

'''

from tkinter import*
root=Tk()
label=Label(root,text="TEMPERATURE CONVERTER")
label.pack(side=TOP)
entry1=Entry(root)
entry1.place(x=300,y=50)
button1=Button(root,text="Convert")
button1.place(x=300,y=100)
label1=Label(root,text="Temperature in Celsius: ")
label1.place(x=100,y=50)
label2=Label(root,text="Temperature in Fahrenheit: ")
label2.place(x=100,y=150)
label3=Label(root)
label3.place(x=300,y=150)
var1=DoubleVar()
entry1=Entry(root,textvariable=var1)
def click1():
    label3.config(str(var1.get)  32 * 1.8)
button1.bind("<Button-1>", click1)

'''

CodePudding user response:

You have multiple problems with your function. Are you even looking for the error messages? Because I got several when I ran your code. (1) Button callbacks are passed a parameter. You weren't looking for one, so you get a TypeError. (2) "var1.get" is a function. To fetch the value, you have to CALL the function. (3) You were multiplying the result of str, instead of multiplying the numbers and converting that. (4) You have to tell config what thing to change. In your case, that's text. (5) Your formula for converting C to F is wrong.

This works, assuming you add root.mainloop() at the end.

def click1(e):
    label3.config(text=str(var1.get() * 1.8   32))

CodePudding user response:

The easiest way to solve this is to assign the function right as you initialize the button.
The code would be:

button1 = Button(root, text="Convert", command=click1)

notice that you do not need parentheses () after the assigned function, because you dont want to execute the function in the assignment ;)

Hope I could help!

  • Related