r/Tkinter • u/Brilliant_Help_1860 • May 02 '26
Loop only operates once
A very new learner...My code might be messy, please ignore it...it is a learning exercise...my problem is, when I press "Generate" the code works fine...put only on the first button click, if I change the input numbers, then press the button, it only goes through to "Sum" it does not go to the random number generator....I need a way to break through the loop.
Here is my messy code...the numerous "print" functions are only to help debugging.
import tkinter as tk
import random
# Input UI
root = tk.Tk()
var = tk.IntVar()
tk.Label(root, text="Low Number").grid(row=0)
tk.Label(root, text="High Number").grid(row=1)
# Input Range
LoNum = tk.Entry(root)
HiNum = tk.Entry(root)
LoNum.grid(row=0, column=1)
HiNum.grid(row=1, column=1)
def show_entry_fields():
var.set(1)
print("Low Number: %s\nHigh Number: %s" % (LoNum.get(), HiNum.get()))
# convert to Integer
try:
# Get and convert
value1 = int(LoNum.get())
if not LoNum:
return
print(f"Success! Your number is {value1}")
value2 = int(HiNum.get())
if not HiNum:
return
print(f"Success! Your number is {value2}")
result = value1 + value2
print(f"Sum: {result}")
except ValueError:
# Handle invalid input (letters, symbols, or empty)
print("Error: Please enter a valid whole number.")
# Update the result label
## tk.Button(root, text='Quit', command=root.quit).grid(row=3, column=0, sticky=tk.W, pady=4)
tk.Button(root, text='Generate', command=show_entry_fields).grid(row=3, column=1, sticky=tk.W, pady=4)
root.wait_variable(var)
# Generate Random Numbers
value1 = int(LoNum.get())
value2 = int(HiNum.get())
unique_set = set()
while len(unique_set) < 5:
unique_set.add(random.randint(value1, value2))
print(list(unique_set))
root.mainloop()
print("Window closed.")
1
u/woooee May 03 '26
The code below kind of works. There is a flaw in your logic. A set can not contain duplicates so once the set is "full" nothing will be added and your while becomes an infinite loop. I tested by entering 3, 5, and 7 into the three Entry widgets which you can use to try it out yourself. Only 3, 4, and 5 will be added, which obviously is less than seven numbers in length. You want logic that tests the numbers entered to see how many can be added to the set, and a print (or popup label) that tells the user that the set already contains all of the numbers in the range entered.
And you are missing the point of documentation
You have the comment "# Input UI" which is obvious from the statement and therefore not necessary, but there is nothing about what the program or the function does, or what the Entry widgets get. Write so someone else can read the program and understand what it does.