[Python] Global module variable doesn't change after being imported [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I have a function that makes two global variables upon import. Another function turns those variables into IntVars, but it doesn't update them for the code that uses the module.

    AliasTkFunctions contains this code, which should set the vars, then change them to IntVars:

    rows_ = None
    columns_ = None


    def initiate_grid(window):
    from tkinter import IntVar
    global rows_, columns_

    rows_ = IntVar()
    rows_.trace("w", lambda *_: [window.rowconfigure(a, weight=1) for a in range(rows_.get())])

    columns_ = IntVar()
    columns_.trace("w", lambda *_: [window.columnconfigure(a, weight=1) for a in range(columns_.get())])

    print("Initiate Grid")


    def grid(window, rows=None, columns=None, clear=True):
    global rows_, columns_

    if clear:
    [b.destroy() for b in window.winfo_children()]

    if rows is not None:
    rows_.set(rows)

    if columns is not None:
    columns_.set(columns)

    print("Grid Changed")


    This code should set the grid to 5x5 and fill everysquare with a random coloured square:

    from tkinter import Tk, Label

    from AliasTkFunctions import fix_resolution_issue, resize_window, initiate_grid, grid
    from AliasColourFunctions import random_hex_colour

    fix_resolution_issue()

    main = Tk()
    resize_window(main, 4, 4, False)
    main.resizable(False, False)
    main.title("Placeholder")

    initiate_grid(main)
    grid(main, 5, 5)

    for c in range(columns_.get() + 1):
    for r in range(rows_.get()):
    Label(background=random_hex_colour()).grid(row=r, column=c, sticky="nsew")


    With this code, it gives me this error:

    Traceback (most recent call last):
    File "C:\Users\dandr\Code\PycharmProjects\Python Projects 2\Random Colours.py", line 16, in <module>
    for c in range(columns_.get() + 1):
    ^^^^^^^^
    NameError: name 'columns_' is not defined
    Initiate Grid
    Grid Changed

    Continue reading...

Compartilhe esta Página