Skip to content Skip to sidebar Skip to footer

Creating A New Variable Using The Def Command In Python

I am trying define a command that creates a new variable based on one of the arguments given for the command. For example: def NewEntry(Variable,Variable_Entry,Column,Row): Var

Solution 1:

To make a global variable, do this (albeit very ugly and not really nice):

def newEntry(Variable): # Variable should be a string
    globals()[Variable] = StringVar()

However, you shouldn't do this. You won't know the variable afterwards!

If you want to store GUI elements, or multiple unknown items, use built-in data types, such as lists and dictionaries. They are much easier to use, and widely accepted.


Solution 2:

You can't set variables by passing them in as arguments. It doesn't work because it doesn't make any sense. What you want is more like this:

def NewEntry(column, row):
    variable = StringVar()
    variable_entry = ttk.Entry(mainframe, width=15, textvariable=variable)
    variable_entry.grid(column=column, row=row)
    return variable, variable_entry

Then, when you call this function, you save its return values in whatever variable names you like:

var, var_entry = NewEntry()

Post a Comment for "Creating A New Variable Using The Def Command In Python"