logo
down
shadow

Creating and assigning multiple variables in a tkinter application


Creating and assigning multiple variables in a tkinter application

By : Ashu
Date : October 23 2020, 08:10 AM
To fix this issue Your syntax is wrong. The i in OptionMenu(self, i, "methane", "eth... is actually a StringVar(), whose value is set when an Optionmenu is selected. So you need to keep a list of it and initialise the corresponding one.
Here is the working code.
code :
from tkinter import OptionMenu
import tkinter as Tkinter

class GasGen(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.vars = []
        self.initialize()
        self.grid()

    def initialize(self):
        for i in range(8):
            t = Tkinter.StringVar()
            t.set("Not Selected")
            self.vars.append(t)

        for i in range(len(self.vars)):
            OptionMenu(self, self.vars[i], "methane", "ethane", "propane", "iso-butane", "n-butane", "iso-pentane", "n-pentane", "benzene").grid(column = 0, row = i)

        Tkinter.Button(text="Show Values", command=self.show).grid(pady=10)

    def show(self):
        Tkinter.Label(text="\n".join([k.get() for k in self.vars])).grid(pady=10)

if __name__ == "__main__":
    app = GasGen(None)
    app.title('Gas mixture generator')
    app.configure(background = "slate gray")
    app.mainloop()


Share : facebook icon twitter icon
Assigning variables using choices in TKInter dropdown menu - Python 2.7

Assigning variables using choices in TKInter dropdown menu - Python 2.7


By : Andrew Ross
Date : March 29 2020, 07:55 AM
I wish this help you I would like to be able to create a dropdown list, and assign each choice in the list a different variable. When the option is selected from the dropdown, I would like an entry box to display the associated variable, not the name of the option. , Try following code. Read a comment I added.
code :
from Tkinter import *
import Tkinter as ttk 
from ttk import *

root = Tk()
root.title("Age Selector")

mainframe = Frame(root)                                 
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 10, padx = 10)

var = StringVar(root)

# Use dictionary to map names to ages.
choices = {
    'Bob': '35',
    'Garry': '45',
    'John': '32',
    'Hank': '64',
    'Tyrone': '21',
}

option = OptionMenu(mainframe, var, *choices)
var.set('Bob')

option.grid(row = 1, column =1)

Label(mainframe, text="Age").grid(row = 2, column = 1)

age = StringVar()
# Bind age instead of var
age_ent = Entry(mainframe, text=age, width = 15).grid(column = 2, row = 2)

# change_age is called on var change.
def change_age(*args):
    age_ = choices[var.get()]
    age.set(age_)
# trace the change of var
var.trace('w', change_age)

root.mainloop()
Python 3.5: Assigning multiple variables using choices in TKInter dropdown menu

Python 3.5: Assigning multiple variables using choices in TKInter dropdown menu


By : Ayemi Williams
Date : March 29 2020, 07:55 AM
hop of those help? OptionMenu after closing dropdown menu can display only one option - so it can't select more options.
So you can use one of this method:
code :
import tkinter as tk

# --- functions ---

def on_button():
    for i, var in enumerate(o_vars):
        print('OptionMenu {}: {}'.format(i, var.get()))
    print()

    print('ListBox:', l.curselection())
    for i in l.curselection():
        print('option:', OPTIONS[i])
    print()

    print('ChecboxBox:')
    for i, var in enumerate(cb_vars):
        if var.get():
            print('option:', OPTIONS[i])

# --- main ---

OPTIONS = ["Script 1","Script 2","Script 3","Script 4","Script 5"]

root = tk.Tk()

# --- OptionMenu ---

tk.Label(root, text='OptionMenus', bg='#aaa').pack(fill='x')

o_vars = []

for i in range(3):
    var = tk.StringVar(value='- select -')
    o_vars.append(var)
    o = tk.OptionMenu(root, var, *OPTIONS)
    o.pack()

# --- Listbox ---

tk.Label(root, text='Listbox', bg='#aaa').pack(fill='x')

l = tk.Listbox(root, selectmode='multiple')
l.pack()
l.insert('end', *OPTIONS)

# --- Checkbuttons ---

tk.Label(root, text='Checkbuttons', bg='#aaa').pack(fill='x')

cb_vars = []
for x in OPTIONS:
    var = tk.BooleanVar(value=False)
    cb_vars.append(var)
    c = tk.Checkbutton(root, text=x, variable=var)
    c.pack()

# --- others ---

b = tk.Button(root, text='OK', command=on_button)
b.pack(fill='x')

root.mainloop()
OptionMenu 1: Script 1
OptionMenu 2: Script 3
OptionMenu 3: Script 5

ListBox: (0, 2, 4)
option: Script 1
option: Script 3
option: Script 5

ChecboxBox:
option: Script 1
option: Script 3
option: Script 5
Creating several tkinter widgets in a for loop and assigning them to variables

Creating several tkinter widgets in a for loop and assigning them to variables


By : RELAYER
Date : March 29 2020, 07:55 AM
hop of those help? The line curRad = 'rad' + str(col) accomplishes absolutely nothing, since the variable gets reassigned on the next line.
The code does not give you any lasting reference to the individual radio buttons - but you don't normally need one: determining which one is selected, or programmatically selecting one, is done via the variable (radVar) that they all share.
code :
allRads = []
allRads.append(curRad)
Creating multiple empty string variables using StringVar() from Tkinter

Creating multiple empty string variables using StringVar() from Tkinter


By : Vikas Chauhan
Date : March 29 2020, 07:55 AM
I wish this helpful for you I need to create a large number of variables that take string input and that initially will be empty (pending user input). , Use a dict.
code :
varlist = {var: StringVar() for var in ["customer_id", "customer_age", "customer_phone"]}
Creating multiple variables and assigning them values using for loop in JS

Creating multiple variables and assigning them values using for loop in JS


By : Jessica Summers
Date : March 29 2020, 07:55 AM
will be helpful for those in need There are a couple problems. First, check your for loop. I think you meant it to be this instead:
code :
for(i=1;i<=3;i++)
var bbb[i]=document.querySelector('.txtt'+i);
Related Posts Related Posts :
  • Submitting login form with scrapy
  • How do i edit the favicon in the Browsable API in Django REST framework?
  • multiprocessing.Pool.map_async doesn't seem to... do anything at all?
  • Python Selenium: Stale Element Reference Exception Error
  • Datetime conversion - How to extract the inferred format?
  • Import YAML variables automatically?
  • How to create a powershell shortcut for my python file
  • Python's 'set' operator doesn't work with numpy.nan
  • Pass object fields and one2many fields on same method - Odoo v8
  • Select columns based on column name and location in Pandas
  • Standardizing timeseries in Pandas using interpolation
  • How many tweets can be collected?
  • how format specifier taking value while tuple list is passed
  • How to print a numpy array with data type?
  • Timeout child thread for python3
  • How can I regroup a dataframe and accumulate a colume's values?
  • Bulk Insert into SQL Server with Python not working
  • Removing last rows of each group based on condition in a pandas dataframe
  • Why the css file can not be found in Django template?
  • targeting center of mass - scipy / numpy
  • Foursquare - get tips from VENUE_ID
  • Unpack a dictionary to format
  • encoding special characters in python2
  • Replacing integers with NaN results in the entire column becoming float dtype
  • Python 3.6 - BeautifulSoup4, parse table AttributeError: ResultSet object has no attribute 'findAll'
  • Convert panda date list to python list of date strings
  • escape response from Scrapy to parse json
  • How to create a same dropdown menu for different labels?
  • Why are some python variables uppercase whereas others are lowercase?
  • Machine Learning, What are the common techniques for feature engineering and presenting the model?
  • Modify value of a Django form field during clean() and validate again
  • Heroku Django app can't start up -- 'No module named site'
  • Getting list of dates (excluding weekends)
  • Im trying to create the regular expression to include the text and not the href
  • Python file.readline(2) reads first 2 charectars
  • Groupby with handling empty bin in python
  • Modifying Gcode
  • calling a value in a dictionary within a dictionary (reading a json file)
  • Bouncing ball invalid syntax why is that?
  • Python making a counter
  • Python rstrip and split
  • What does the String mean in numpy.r_?
  • How to correctly extend variable __all__ in a __init__.py?
  • Python behaves weird with piped input
  • Python 3 two dimensional list comprehension
  • How to slice image by broadcasting slices? Error: 'only integer scalar arrays can be converted to a scalar index' in pyt
  • (Python Beginner) Need a start on classes
  • IndexError: At least one sheet must be visible
  • How to solve a system of linear equations over the nonnegative integers?
  • Pandas keep the most complete rows
  • "List index out of range" error in Python Memory Match game
  • Numpy: how to use argmax results to get the actual max?
  • Google Cloud Dataflow can't import 'google.cloud.datastore'
  • Calculate pandas DataFrame column by custom routine which accepts dictionary as input
  • Connect to a Class Method by it's method name holded into a var in a for loop in python
  • PyQt5 signals and threading.Timer
  • Replace 2 characters in a string in python
  • Passing command line arguments from a folder script to a file script
  • Understand the syntaxe X[Y == c] in Numpy
  • Optimize beginner python script about substring replacement
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org