1

I'm trying to create a small GUI that when the user enters a number into a text box, and it displays (as a label) whether it is a prime number or not.

The code I have currently "works" (as in no errors are displayed) but the label doesn't change.

The prime number code works in the python shell.

My code is as follows:

from tkinter import *

root = Tk()

label1 = Label( root, text="Enter Number")
E1 = Entry(root, bd =5)

def isPrime():
    entry1 = E1.get()
    entry1 = int(entry1)
    for d in range(2,entry1):
        if entry1 % d == 0:
            label1 = Label(root, text="Not prime")
            root.update_idletasks()
            break
    else:
        label1 = Label(root, text="Is prime")


submit = Button(root, text ="Submit", command = isPrime)
root.update_idletasks()

label1.pack()
E1.pack()
submit.pack(side =BOTTOM) 
root.mainloop()

Thanks for any help in advance, and please let me know if you'd like any more clarification about any issues. Thanks.

7
  • All those people using Tkinter still today... Commented Apr 25, 2016 at 13:47
  • 1
    You are replacing the label with a new one, instead of changing the existing Label. You should do label1["text"] = "Is prime" for example. Commented Apr 25, 2016 at 13:51
  • 1
    @AmitGold if you know the answer you should not be clicking the "Add Comment" button to post the answer. Commented Apr 25, 2016 at 14:00
  • @linusg what would you recommend instead of Tkinter for making GUIs with python? Commented Apr 25, 2016 at 14:14
  • @TadhgMcDonald-Jensen I was reviewing so I didn't have the button. Commented Apr 25, 2016 at 14:17

1 Answer 1

1

You are re-creating the label1 everytime you click on button. Also, you are not packing the one you are creating since that one is in local scope of isPrime() method.

If you want to change the text of the label, you should pass it as parameter to isPrime() and use .config(text="text here") or label["text"] = "text here".

def isPrime(lbl):
    entry1 = int(E1.get())
    for d in range(2,entry1):
        if entry1 % d == 0:
            lbl.config(text = "Not prime")
            break
    else:
        lbl["text"] = "Prime"

submit = Button(root, text ="Submit", command = lambda:isPrime(label1))

or you can make label1 global and change its text.

def isPrime():
    global label1
    entry1 = E1.get()
    entry1 = int(entry1)
    for d in range(2,entry1):
        if entry1 % d == 0:
            label1.config(text = "Not prime")
            break
    else:
        label1["text"] = "Prime"

submit = Button(root, text ="Submit", command = isPrime)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.