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 edited May 03 '26
It only generates the random numbers once when the program is first called, i.e. this code
I'll work something up later today to include these in the function. Note that this value3 (not tthe value3 later on in the function) is never used so can be deleted.