I am creating a GUI that builds information about a person. I want the user to select their birth month using a drop down bar, with the months configured earlier as a list format.
from tkinter import *
birth_month = [
'Jan',
'Feb',
'March',
'April'
] #etc
def click():
entered_text = entry.get()
Data = Tk()
Data.title('Data') #Title
label = Label(Data, text='Birth month select:')
label.grid(row=2, column=0, sticky=W) #Select title
How can I create a drop down list to display the months?
To create a "drop down menu" you can use OptionMenu in tkinter
Example of a basic OptionMenu:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
Here Is my function which will let you create a Combo Box with values of files stored in a Directory and Prints the Selected Option value in a Button Click.
from tkinter import*
import os, fnmatch
def submitForm():
strFile = optVariable.get()
# Print the selected value from Option (Combo Box)
if (strFile !=''):
print('Selected Value is : ' + strFile)
root = Tk()
root.geometry('500x500')
root.title("Demo Form ")
label_2 = Label(root, text="Choose Files ",width=20,font=("bold", 10))
label_2.place(x=68,y=250)
flist = fnmatch.filter(os.listdir('.'), '*.mp4')
optVariable = StringVar(root)
optVariable.set(" Select ") # default value
optFiles = OptionMenu(root, optVariable,*flist)
optFiles.pack()
optFiles.place(x=240,y=250)
Button(root, text='Submit', command=submitForm, width=20,bg='brown',fg='white').place(x=180,y=380)
root.mainloop()
Related
I am attempting to create an arbitrary number of optionmenus, but have trouble when trying to pull the StringVar() selected by each optionmenu.
Goal: Create an arbitrary number of optionmenus with consecutive names (up to that arbitrary number) and consecutive variable names keeping track of the current optiomenu value
For example if an optionmenu is as follows:
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.geometry()
dropdown1 = StringVar()
Dropdownoptions = [
"option1",
"option2",
"option3"
]
dropdownfirst = tk.OptionMenu(root, dropdown1, *Dropdownoptions)
dropdownfirst.grid(column=0, row=0)
root.mainloop()
If using a dictionary I do not know how to pull the values out of each Optionmenu. When looking at other questions about the use of dictionaries to create variables, most answers boil down to "Learn How to Use Dictionaries" instead of answering the questions.
There was a very similar problem posted in Tkinter Create OptionMenus With Loop but sadly it is not applicable in my case.
New code with grid and non-working button:
import tkinter as tk
def erase_option():
for (name, var) in options.items():
print(var.get())
# print(options['optionmenu4'])
# This just places label over dropdown, doesnt successfully take place for removal
labelforemoval = tk.Label(text=" ")
labelforemoval.grid(column=0, row=4)
labelforemoval.grid_forget()
root = tk.Tk()
Dropdownoptions = [
"option1",
"option2",
"option3"
]
maxval = 10
options = {}
for om, x in zip(range(maxval), range(maxval)):
name = f"optionmenu{om}"
var = tk.StringVar()
options[name] = var
name = tk.OptionMenu(root, var, *Dropdownoptions)
name.grid(column=0, row=x)
button = tk.Button(root, text="Erase 5th option", command=erase_option)
button.grid(column=0, row=maxval)
root.mainloop()
Give each optionmenu its own StringVar instance. Save those instances in a list or dictionary. To get the values, iterate over the list.
The following code creates a dictionary named options. It creates a series of variables and optionmenus in a loop, adding each variable to this options dictionary. The function print_options iterates over the list printing out the key and value for each option.
import tkinter as tk
def print_options():
for (name, var) in options.items():
print(f"{name}: {var.get()}")
root = tk.Tk()
Dropdownoptions = [
"option1",
"option2",
"option3"
]
options = {}
for om in range(10):
name = f"Option {om}"
var = tk.StringVar(value="")
options[name] = var
om = tk.OptionMenu(root, var, *Dropdownoptions)
om.pack()
button = tk.Button(root, text="Print Options", command=print_options)
button.pack(side="bottom")
root.mainloop()
I made a new object of tk.IntVar and called it pwHardness
but its value is something random like 140358607937898IntVar.
i want the radio buttons to set the value of the variable pwHardness 1 or 2
import tkinter as tk
pwHardness = tk.IntVar
window = tk.Tk()
window.geometry("1600x500")
window.configure(bg="#323e52")
Label = tk.Label(text="Password Gen", background="#323e52", foreground="#fafafa")
Label.config(width=200)
Label.config(font=("Courier", 44))
setPwRadioButtonEasy = tk.Radiobutton(
text="Easy PW",
padx = 20,
var=pwHardness,
variable=pwHardness,
value=1,
)
setPwRadioButtonHard = tk.Radiobutton(
text="Hard PW",
padx = 20,
var=pwHardness,
variable=pwHardness,
value=2,
)
label1 = tk.Label(text=pwHardness)
Label.pack()
setPwRadioButtonEasy.pack()
setPwRadioButtonHard.pack()
label1.pack()
window.mainloop()
FYI This is going to be a Password Generator.
You aren't initializing the variable, you're just taking the IntVar object.
pwHardness = tk.IntVar()
would initialize a new IntVar – you're missing the parentheses.
Additionally, you're passing the var as a "string" value to text.
You'd want
label1 = tk.Label(text=pwHardness.get())
to "read" the variable into the label. However, it won't refresh automatically with that configuration.
You are missing parentheses after pwHardness = tk.IntVar. It should be pwHardness = tk.IntVar(). Additionally, change label1 = tk.Label(text=pwHardness) to label1 = tk.Label(textvar=pwHardness), so the label gets automatically updated. And, tk.IntVar must be initiated with a parent, e.g. the toplevel window. Example :
import tkinter as tk
root = tk.Tk()
var = tk.IntVar(root)
label = tk.Label(root, textvar=var)
label.pack()
while True:
inp = input("enter new value ")
if inp != "quit":
var.set(int(inp))
else:
break
Ok, so basic story. I have created an entry. After you introduce text, you have to click a button to store the inputted text into a variable that is later printed.
Here is the code:
from Tkinter import *
def myClick(entry_name, var):#defines function to get input from entry and store into var
var = entry_name.get()
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
hello = None #variable to store entry input
bt1 = Button(root, command = myClick(ent, hello))#button 1 creation and function attribution
bt1.grid(row = 3, column = 0)#button 1 griding
root.mainloop()
print(hello)
It is very unclear to me why the function does not get the input from the entry.
bt1 = Button(root, command = myClick(ent, hello))
In this line, you call myClick function with parameters, not just pass it. That means that myClick is executed once after the module is launched and then it does nothing. If you want to print the entry input, I recommend you do the following:
from tkinter import *
root = Tk()
lbl1 = Label(root, text="hello")
lbl1.grid(row=0, column=0)
ent = Entry(root, width=15)
ent.grid(row=1, column=0)
def myClick():
var = ent.get()
print(var)
bt1 = Button(root, command=myClick)
bt1.grid(row=3, column=0)
root.mainloop()
Also code after root.mainloop() doesn't excecute.
just define a normal function :
from tkinter import *
def blinta():
var = ent.get()
ent.delete(0,END)
print(var)
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
bt1 = Button(root, command = blinta)
bt1.grid(row = 3, column = 0)
root.mainloop()
This will work I'm sure.
I'm trying to make a label that will change when I enter text into the entry box and click the button.
I've tried doing some research but can't seem to find out how to do it .
from tkinter import *
master = Tk()
master.title("Part 3")
v = StringVar()
v.set("Please change me")
lb= Label(master, textvariable=v, fg="red",bg="black").grid(row=0,column=0)
ent= Entry(master, textvariable=v,).grid(row=1,column=2)
b1= Button(master, text="Click to change", fg="red",bg="black").grid(row=1,column=0)
to do so, you first need to define a callback that changes the value. (example below)
You should also use two Variables of type StringVar to store the different Values
from tkinter import *
master = Tk()
master.title("Part 3")
lText = StringVar()
lText.set("Please change me")
eText = StringVar()
def ChangeLabelText(event=None):
global lText
global eText
lText.set(eText.get())
Then, bind the callback to the button
lb = Label(master, textvariable=lText, fg="red",bg="black").grid(row=0,column=0)
ent = Entry(master, textvariable=eText).grid(row=1,column=2)
b1 = Button(master, text="Click to change", fg="red",bg="black", command=ChangeLabelText).grid(row=1,column=0)
I'm trying to update the content of a label, in Python, by clicking a button. For each clicks a counter will be raised and the value of the label will be updated by the current value of the counter (j). Here is the code:
import time
import random
import MySQLdb
from Tkinter import *
j=0
def PrintNumber():
global j
j+=1
print j
return
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
st = Button(mgui, text="Next Customer", command = PrintNumber)
st.pack()
f = PrintNumber()
label = Label(mgui, text=f)
label.pack()
mgui.mainloop()
Please be kind, i'm new in Python. :)
You can use a Tkinter variable class instance to hold a value. If you assign the textvariable option of the Label widget to the variable class instance, it will update automatically as the value of the instance changes. Here's an example:
from Tkinter import *
root = Tk()
var = IntVar() # instantiate the IntVar variable class
var.set(0) # set it to 0 as the initial value
# the button command is a lambda expression that calls the set method on the var,
# with the var value (var.get) increased by 1 as the argument
Button(root, text="Next Customer", command=lambda: var.set(var.get() + 1)).pack()
# the label's textvariable is set to the variable class instance
Label(root, textvariable=var).pack()
mainloop()
You can change the label text in the function that responds to the command (PrintNumber() in this case) using label.config(), e.g.:
from tkinter import *
def PrintNumber():
global j,label
j+=1
label.config(text=str(j))
return
j = 0
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
st = Button(mgui, text="Next Customer", command = PrintNumber)
st.pack()
label = Label(mgui, text=str(j))
label.pack()
mgui.mainloop()
Here is another way you could do it
import time
import random
import MySQLdb
from Tkinter import *
def PrintNumber(label):
PrintNumber.counter += 1 #simulates a static variable
print PrintNumber.counter
label.configure(text=str(PrintNumber.counter)) #you update label here
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
PrintNumber.counter = 0 #add an attribute to a function and use it as a static variable
label = Label(mgui) #create label
#pass the label as parameter to your function using lambda notation
st = Button(mgui, text="Next Customer", command=lambda label=label:PrintNumber(label))
st.pack()
label.pack()
mgui.mainloop()