pythontkinterjedit

Python, Tkinter, trying to pull random numbers from a list based off user input for number and have results open in mew window


Title pretty much sums it up, pasting the script below. Anytime its run the following error is generated. I am extremely new to python and tkinter. So you know supernoob! But I appreciate help on this and if it's something I can't find a post of in the forums I will happily ask the question and pray that I can get a solid answer and explanation about how the code should be. Tim the answer and example you provided worked perfectly. However I did have another concept that's tied into this. How would you modify the script to two input boxes that display on the same popup?

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.496.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py", line 2068, in __call__
    return self.func(*args)
           ~~~~~~~~~^^^^^^^
  File "C:\Users\falso\Desktop\Development\Software\1.py", line 10, in generate_random_value
    result_label.config(text=random_values)
    ^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'result_label' where it is not associated with a value

Here is current script

import tkinter as tk
import random


def generate_random_value():
    try:
        num_values = int(entry.get())
        if num_values > 0 and num_values <= len(my_list):
            random_values = random.sample(my_list, num_values)
            result_label.config(text=random_values)
            new_window = Toplevel(window)
            new_window.title("Oops!!")
            result_label=Label(new_window, text='result')
            result_label.pack()
            new_window.mainloop()
        else:
            result_label.config(text="Invalid input")
            result_label.pack_forget()
    except ValueError:
        result_label.config(text="Invalid input")
           
window=tk.Tk()
window.title("Random Value Generator")

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

entry = tk.Entry(window)
entry.pack()

button = tk.Button(window, text="Generate", command=generate_random_value)
button.pack()


result_label = tk.Label(window, text="")
result_label.pack()

window.mainloop()

Hit a dead end with zero results.  Tried a few manipulations and renaming with no luck.

Solution

  • Your main issue is that you are reusing the name "result_label", which breaks the connection with your global. And you don't need to create a second mainloop. You need exactly one mainloop call in any given program.

    This seems to do what you want:

    import tkinter as tk
    import random
    
    def generate_random_value():
        try:
            num_values = int(entry.get())
            if num_values > 0 and num_values <= len(my_list):
                random_values = random.sample(my_list, num_values)
                new_window = tk.Toplevel(window)
                new_window.title("Wow!!")
                xresult_label=tk.Label(new_window, text='result')
                xresult_label.pack()
                xresult_label.config(text=random_values)
            else:
                result_label.config(text="Invalid input")
                result_label.pack_forget()
        except ValueError:
            result_label.config(text="Invalid input")
               
    window=tk.Tk()
    window.title("Random Value Generator")
    
    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    
    entry = tk.Entry(window)
    entry.pack()
    
    button = tk.Button(window, text="Generate", command=generate_random_value)
    button.pack()
    
    result_label = tk.Label(window, text="")
    result_label.pack()
    
    window.mainloop()