Skip to content
Advertisement

How can I convert a return statement into something that can be used by Tkinter [closed]

I am making a GFC (Greatest Common Factor) calculator with GUI, but my current code only works with a return statement, and tkinter doesn’t accept return to fill a textbox widget.

Here is a sample of my code

def gproces():
    Gnumber1 = Entry.get(GE1)
    Gnumber2 = Entry.get(GE2)
    Gnumber1 = int(Gnumber1)
    Gnumber2 = int(Gnumber2)

    if Gnumber1 > Gnumber2:
        Gnumber1, Gnumber2 = Gnumber2, Gnumber1

    for x in range (Gnumber1, 0, -1):
        if Gnumber1 % x == 0 and Gnumber2 % x == 0:
            return x

Here is where it’s supposed to be used: (To fill GE3)

GE3=Entry(top, bd =5)
GE3.grid(row=3, column=4)
GB=Button(top, text ="Submit", command = gproces).grid(row=4,column=4,)

How do I convert a return statement into something that can be used by Tkinter?

Advertisement

Answer

You can just insert the result into the text box inside gprocess():

def gproces():
    # better cater invalid input
    try:
        Gnumber1 = int(GE1.get())
        Gnumber2 = int(GE2.get())

        x = min(Gnumber1, Gnumber2)
        for x in range(x, 0, -1):
            if Gnumber1%x == 0 and Gnumber2%x == 0:
                break

        # insert result into text box
        GE3.delete(0, 'end')
        GE3.insert('end', x)
    except ValueError:
        print('Invalid number input')

Note that there is math.gcd() to find the GCF.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement