Home > Mobile >  Python TKINTER label not showing up
Python TKINTER label not showing up

Time:05-12

I have the following code that I wrote for a calculator for my college coding class. For some reason, the label I added does not show up. I inititally used a text box, which I couldn't update, before switching it to a label. Can anyone tell me why it is not appearing? I can't see any reason why it wouldn't be showing up there.

from tkinter import *

root = Tk()
root.geometry('100x100')
root.title("calculator")




display ="0"
holder = "0"
operand = 0

text_box = Label(
  
    textvariable = display

)
text_box.grid(row = 0, column = 0)





def adddigit(num):
    global display
    if display == "0":
        display = num
    else:
        display  = num
    print(display)
        
def add():
    global display
    global holder
    global operand
    holder = display
    operand = 1
    display = "0"
    

def subtract():
    global display
    global holder
    global operand
    holder = display
    operand = 2
    display = "0"
def solve():
    global display
    global holder
    global operand
    if operand == 1:
        display = str(int(display)   int(holder))
    elif operand == 2:
        holder = str(int(holder)-int(display))
        display = holder
    
        
    print(display)
btnTest = Button(text = display)
btnTest.grid(row=0,column=1)
btn1 = Button(text = "1", command = lambda: adddigit("1"))
btn1.grid(row=1,column=0)
btn2 = Button(text = "2", command = lambda: adddigit("2"))
btn2.grid(row=1,column=1)
btn3 = Button(text = "3", command = lambda: adddigit("3"))
btn3.grid(row=1,column=2)
btn4 = Button(text = "4", command = lambda: adddigit("4"))
btn4.grid(row=2,column=0)
btn5 = Button(text = "5", command = lambda: adddigit("5"))
btn5.grid(row=2,column=1)
btn6 = Button(text = "6", command = lambda: adddigit("6"))
btn6.grid(row=2,column=2)
btn7 = Button(text = "7", command = lambda: adddigit("7"))
btn7.grid(row=3,column=0)
btn8 = Button(text = "8", command = lambda: adddigit("8"))
btn8.grid(row=3,column=1)
btn9 = Button(text = "9", command = lambda: adddigit("9"))
btn9.grid(row=3,column=2)
btn0 = Button(text = "0", command = lambda: adddigit("0"))
btn0.grid(row=4,column=1)
btnadd = Button(text = " ", command = add)
btnadd.grid(row = 5, column = 0)
btnsub = Button(text = "-", command = subtract)
btnsub.grid(row = 5, column = 1)
btnsolve = Button(text = "=", command = solve)
btnsolve.grid(row = 5, column = 2)

CodePudding user response:

The variable passed to the textvariable parameter shouldn't be a string, it should be a tkinter.StringVar() object.

Add the line label_show = tkinter.StringVar(), change the label line to text_box = Label(textvariable=label_show), then at the end of each function, add label_show.set(display)

CodePudding user response:

You need to do:

text_box=Label(root, textvariable=display)
text_box.grid(column=0, row=0)
  • Related