[Python] Python, Tkinter, trying to pull random numbers from a list based off user input for...

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    Title pretty much sums it up, pasting the script below. Anytime its run the following error is generated

    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("Fuck!!")
    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

    Continue reading...

Compartilhe esta Página