I'm able to select both the combo box successfully but to print the second dropdown box value, I got lost. Could somebody explain how to print the Table value from the 2nd drop down box.
Note: The two drop downs are dependabale.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("ETL")
Environment = ["UAT","ITEST","PROD"]
Tables = [["USER_UAT","IP_UAT"],
["USER_ITEST","IP_ITEST"],
["USER_PROD","IP_PROD"]]
envi= ttk.Combobox(root,width =37, value=(Environment))
envi.grid(row=3,column=1,columnspan=2, padx=10, pady=2, sticky='w')
def callback(eventObject):
abc = eventObject.widget.get()
en = envi.get()
index=Environment.index(en)
tab.config(values=Tables[index])
tab=ttk.Combobox(root, width=37)
tab.grid(row=4,column=1,columnspan=2, padx=10, pady=2, sticky='w')
tab.bind('<Button-1>', callback)
root.mainloop()
The most straightforward way is to add a separate event binding for each combobox. I changed the bindings from <Button-1> to <<ComboBoxSelect>> as this prevents the events from being fired every time a combobox is clicked - instead, events will only fire when a selection is actually made.
I also added some code to set the combobox default values as well as to update the value of the second combobobox whenever a selection is made in the first combobox.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('ETL')
environment = ['UAT', 'ITEST', 'PROD']
tables = [
['USER_UAT', 'IP_UAT'],
['USER_ITEST', 'IP_ITEST'],
['USER_PROD', 'IP_PROD'],
]
def populate_table_combobox(event):
index = environment.index(env_combo.get())
table_combo.config(values=tables[index])
table_combo.current(0) # update the 'table' selection when 'env' changes
def get_table_combo_value(event):
print(table_combo.get()) # YOUR CODE HERE!
env_combo = ttk.Combobox(root, width=37, value=environment)
env_combo.current(0) # set default value
env_combo.grid(row=3, column=1, columnspan=2, padx=10, pady=2, sticky='w')
table_combo = ttk.Combobox(root, width=37, values=tables[0])
table_combo.current(0) # set default value
table_combo.grid(row=4, column=1, columnspan=2, padx=10, pady=2, sticky='w')
env_combo.bind('<<ComboBoxSelected>>', populate_table_combobox)
table_combo.bind('<<ComboBoxSelected>>', get_table_combo_value)
root.mainloop()
Related
I'm trying to build a very simple program in Python and Tkinter that allows the user to input people's names by keyboard and then a button is commanded to select a person from the list at random and show it in a tk.Label object.
My problem is once I run the root.mainloop(), I can add names to the list but the list does not update with the new names.
This is the main code for the Tkinter to initialize
import tkinter as tk
from tkinter import filedialog, Text
import random
root = tk.Tk()
root.title('Millor persona del moment')
root.geometry("500x200")
root.configure(bg='black')
peopleList = []
tk.Label(root, text="Insertar participante: ",fg="#ff007f", bg='black').grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0, column=1)
addButton = tk.Button(root, text='Añadir', padx=10, pady=5, fg="#ff007f", bg='black', command=addPerson)
addButton.grid(row=0, column=2)
while peopleList:
turnButton = tk.Button(root, text='Saca Tema', padx=10, pady=5, fg="#ff007f", bg='black', command=wordTurn(peopleList))
turnButton.grid(row=1, column=0)
nom = tk.StringVar()
nom.set('Comencem')
personSpeaking = tk.Label(root, textvariable=nom,fg="#ff007f", bg='black')
personSpeaking.grid(row=1, column=1)
root.mainloop()
And these are the functions I use
def addPerson():
peopleList.append(e1.get())
e1.delete(0,'end')
def wordTurn(peopleList):
person = random.choice(peopleList)
peopleList.remove(person)
nom.set(person)
command=wordTurn(peopleList)) calls the return value of wordTurn when the button is pressed, which is None and should raise an error. Use command=lambda peopleList=peopleList: wordTurn(peopleList)) instead.
How can I make windows show up one at a time with tkinter? For example, if I typed in 6 as an input, and called a function with a button, I need it to show me 6 windows, but one at a time. It will only prompt me the next window after pressing a button from the previous one.
I tried using a for loop to loop through the range of the input, and create new windows with a button based on that range, but the problem is that they all show up at the same time:
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("Multiple windows")
def multiplewindows():
for i in range(int(number.get())):
tempwindow = Toplevel()
tempwindow.title(f"Window {i+1}")
tempbutton = Button(tempwindow, text=f"Button {i+1}")
tempbutton.pack(padx=10, pady=10)
number = Entry(root, width=5)
number.pack(padx=10, pady=10)
button = Button(root, text="Show", command=multiplewindows)
button.pack(padx=10, pady=10)
root.mainloop()
Is there any way to pause the for loop and allow it to continue after pressing the button in the newly created window?
I think you don't need for loop to do this
def multiplewindows():
j=int(number.get())
tempwindow = Toplevel()
tempwindow.title(f"Window {j}")
tempbutton = Button(tempwindow, text=f"Button {j}")
tempbutton.pack(padx=10, pady=10)
And if you want to use for loop to do this
def multiplewindows():
j=int(number.get())
for i in range(int(number.get())):
if (i+1)==j:
tempwindow = Toplevel()
tempwindow.title(f"Window {j}")
tempbutton = Button(tempwindow, text=f"Button {j}")
tempbutton.pack(padx=10, pady=10)
The easiest way to do this is like acw1668 was recommanded with the builtin method of tkinter that is calld with wait_window().
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("Multiple windows")
def multiplewindows():
for i in range(int(number.get())):
tempwindow = Toplevel()
tempwindow.title(f"Window {i+1}")
tempbutton = Button(tempwindow, text=f"Button {i+1}", command=tempwindow.destroy)
tempbutton.pack(padx=10, pady=10)
tempwindow.wait_window()
number = Entry(root, width=5)
number.pack(padx=10, pady=10)
button = Button(root, text="Show", command=multiplewindows)
button.pack(padx=10, pady=10)
root.mainloop()
Here we have created a function with a forloop that waits until the window is destroyed and added a command to the Button to destroy the window.
I have a GUI using Tkinter, it has a main screen and then when you press a button a popup window appears, where you select a checkbutton and then a email will get sent to you.
Not matter what I do, I cannot read the value of the checkbutton as 1 or True it always = 0 or False.
This is my code:
import tkinter as tk
from tkinter import *
import time
root = tk.Tk()
root.title('Status')
CheckVar1 = IntVar()
def email():
class PopUp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
popup = tk.Toplevel(self, background='gray20')
popup.wm_title("EMAIL")
self.withdraw()
popup.tkraise(self)
topframe = Frame(popup, background='gray20')
topframe.grid(column=0, row=0)
bottomframe = Frame(popup, background='gray20')
bottomframe.grid(column=0, row=1)
self.c1 = tk.Checkbutton(topframe, text="Current", variable=CheckVar1, onvalue=1, offvalue=0, height=2, width=15, background='gray20', foreground='snow', selectcolor='gray35', activebackground='gray23', activeforeground='snow')
self.c1.pack(side="left", fill="x", anchor=NW)
label = tk.Label(bottomframe, text="Please Enter Email Address", background='gray20', foreground='snow')
label.pack(side="left", anchor=SW, fill="x", pady=10, padx=10)
self.entry = tk.Entry(bottomframe, bd=5, width=35, background='gray35', foreground='snow')
self.entry.pack(side="left", anchor=S, fill="x", pady=10, padx=10)
self.button = tk.Button(bottomframe, text="OK", command=self.on_button, background='gray20', foreground='snow')
self.button.pack(side="left", anchor=SE, padx=10, pady=10, fill="x")
def on_button(self):
address = self.entry.get()
print(address)
state = CheckVar1.get()
print (state)
time.sleep(2)
self.destroy()
app = PopUp()
app.update()
tk.Button(root,
text="EMAIL",
command=email,
background='gray15',
foreground='snow').pack(side=tk.BOTTOM, fill="both", anchor=N)
screen = tk.Canvas(root, width=400, height=475, background='gray15')
screen.pack(side = tk.BOTTOM, fill="both", expand=True)
def latest():
#Other code
root.after(300000, latest)
root.mainloop()
The popup works perfectly, and the email will print when entered but the value of checkbox is always 0.
I have tried:
CheckVar1 = tk.IntVar() - No success
self.CheckVar1 & self.CheckVar1.get() - No success
Removing self.withdraw() - No success
I only have one root.mainloop() in the script, I am using app.update() for the popup window because without this it will not open.
I have checked these existing questions for solution and none have helped:
Self.withdraw - Can't make tkinter checkbutton work normally when running as script
Self.CheckVar1 - TKInter checkbox variable is always 0
Only one instance of mainloop() - Python tkinter checkbutton value always equal to 0
I have also checked very similar questions but I wasn't going to post them all.
Any help is appreciated.
The problem is that you have two root windows. Each root window gets its own internal tcl interpreter, and the widgets and tkinter variables in one are completely invisible to the other. You're creating the IntVar in the first root window, and then trying to associate it with a checkbutton in a second root window. This cannot work. You should always only have a single instance of Tk in a tkinter program.
because of variable scope
try to put CheckVar1 = IntVar() inside the class
use it with self like this
self.CheckVar1 = tk.IntVar() # object of int
self.CheckVar1.set(1) # set value
variable=self.CheckVar1 # passing to the checkbutton as parameter
state = self.CheckVar1.get() # getting value
I am creating a section anlysis GUI in python using tkinter.
I've created a drop down list and the interface can changes with different choice, but upon selecting for the second time, it seems the new interface(some entry or text) just covers the first interface.
I want to know how to delete the first interface so that interface can immediately update with the selection in dropdownlist.
Here is the code:
import tkinter as tk
import tkinter.ttk
def secdata( *args ):
t = sectype.get()
if t=='Rec_Shape':
tk.ttk.Label(monty1, text="REC_Width").grid(column=0, row=1)
wid=tk.StringVar()
widdata=tk.ttk.Entry(monty1,width=5,textvariable=wid)
widdata.grid(column=1,row=1)
tk.ttk.Label(monty1, text="REC_Height").grid(column=0, row=2)
hei=tk.StringVar()
heidata=tk.ttk.Entry(monty1,width=5,textvariable=hei)
heidata.grid(column=1,row=2)
else:
tk.ttk.Label(monty1, text="Flange_Width").grid(column=0, row=1)
wid1=tk.StringVar()
wid1data=tk.ttk.Entry(monty1,width=5,textvariable=wid1)
wid1data.grid(column=1,row=1)
tk.ttk.Label(monty1, text="Web_Width").grid(column=0, row=2)
wid2=tk.StringVar()
wid2data=tk.ttk.Entry(monty1,width=5,textvariable=wid2)
wid2data.grid(column=1,row=2)
tk.ttk.Label(monty1, text="Flange_Height").grid(column=0, row=3)
hei1=tk.StringVar()
hei1data=tk.ttk.Entry(monty1,width=5,textvariable=hei1)
hei1data.grid(column=1,row=3)
tk.ttk.Label(monty1, text="Total_Height").grid(column=0, row=4)
hei2=tk.StringVar()
hei2data=tk.ttk.Entry(monty1,width=5,textvariable=hei2)
hei2data.grid(column=1,row=4)
window=tk.Tk()
window.title('Section Analysis')
window.geometry('500x400')
tabControl=tk.ttk.Notebook(window)
tab1=tk.ttk.Frame(tabControl)
tabControl.add(tab1,text='Bending')
tabControl.pack(expand=1,fill='both')
monty1=tk.ttk.LabelFrame(tab1,text='Bending')
monty1.grid(column=0, row=0, padx=8, pady=4)
tk.ttk.Label(monty1, text="Sectype:").grid(column=0, row=0, sticky='W')
sectype=tk.ttk.Combobox(monty1,state='readonly')
sectype.grid(column=1, row=0)
sectype['value']=('Rec_Shape','T_Shape')
sectype.current(0)
sectype.bind("<<ComboboxSelected>>",secdata)
monty1.mainloop()
window.mainloop()
I've been working with Tkinter and I'm having a problem with spinbox. I have spinbox set to: from_=1, to=5. No mater what I do spinbox outputs a 5 as it's variable. I've read lot's of post here on other's answer for related questions and can't seem to find an answer.
Clicking the mouse and selecting a value in the spinbox does nothing.
Here is the code :
sp1=Spinbox(root, bd=3, state='readonly', from_=1, to=5, font="bold", wrap="true")
sp1.grid(row=3, column=2, padx=20)
sp1.delete(0, END)
sp1.bind("<Button-1>")
i=sp1.get()
i is always equal to 5.
You can assign function to Spinbox using command= and this function will be executed everytime you change value in Spinbox. And then you can get value from Spinbox. Now you get value only at start.
import tkinter as tk
# --- functions ---
def callback():
print("value:", w.get())
# --- main ---
root = tk.Tk()
w = tk.Spinbox(root, state='readonly', from_=1, to=5, command=callback)
w.pack()
root.mainloop()
You can pass a callback function to the command argument when you initialize the Spinbox:
# python 3
from tkinter import *
# python 2
#from Tkinter import *
root = Tk()
def on_spinbox_change():
print(sp1.get())
sp1 = Spinbox(root, bd=3, state='readonly', from_=1, to=5, font="bold", wrap="true", command=on_spinbox_change)
sp1.grid(row=3, column=2, padx=20)
root.mainloop()