Show label if combobox value is selectek Tkinter Python3 - python

I need to show/add a label and a textbox when I select a certain value in the combobox. I found this question and it helped but I still didn't get the desired output.
the purpose is the show the label vlan and the textbox when I select the value Single tagged in the combobox.
This is my code :
from tkinter import ttk
from tkinter import messagebox
from tkinter import Tk
from tkinter import Label, Entry, StringVar
root = Tk()
root.title('Traffic generation')
root.geometry('250x250')
ttk.Label(root, text = "Traffic generation",
background = 'light blue', foreground ="white",
font = ("Times New Roman", 15)).grid(row = 0, column = 1, sticky='NESW')
cmb = ttk.Combobox(root, width="10", values=(' Untagged',' Single tagged',' Double tagged'))
def handler(event):
current = cmb.current()
if current == ' Single tagged':
labelText=StringVar()
labelText.set("VLAN")
labelDir=Label(root, textvariable=labelText, height=4)
labelDir.grid(row=2,column=0,sticky='s')
directory=StringVar(None)
dirname=Entry(root,textvariable=directory,width=50)
dirname.grid(row=2,column=1,sticky='e')
#cmb = Combobox
cmb.bind('<<ComboboxSelected>>', handler)
cmb.grid(row=1,column=0,sticky='s')
class TableDropDown(ttk.Combobox):
def __init__(self, parent):
self.current_table = tk.StringVar() # create variable for table
ttk.Combobox.__init__(self, parent)# init widget
self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices"])
self.current(0) # index of values for current table
self.place(x = 50, y = 50, anchor = "w") # place drop down box
def checkcmbo():
if cmb.get() == " Untagged":
messagebox.showinfo("What user choose", "you chose Untagged")
elif cmb.get() == " Single tagged":
messagebox.showinfo("What user choose", "you choose Single tagged")
elif cmb.get() == " Double tagged":
messagebox.showinfo("What user choose", "you choose Double tagged")
elif cmb.get() == "":
messagebox.showinfo("nothing to show!", "you have to be choose something")
cmb.place(relx="0.1",rely="0.1")
btn = ttk.Button(root, text="Select mode",command=checkcmbo)
btn.place(relx="0.5",rely="0.1")
root.mainloop()

The problem is that Combobox.current() will return the index not the value.
There are two solutions:
change if current == ' Single tagged': to if current == 1.
change if current == ' Single tagged': to if cmb.get() == ' Single tagged':.

Related

Text Field that appears if user choose Yes in the combo box in tkinter

I want to add a text field and input text if the user choose "Yes" in the combo box; other wise nothing will be added. Tried this but didn't work
Combo = ttk.Combobox(window, values = vlist)
Combo.set("Pick an Option")
Combo.pack()
if (Combo.get()=="Yes"):
tkinter.Label(window, text="Number of Workers", bg = "white",fg = "black", font=("Times",13,"bold")).place(x=155,y=240)
inputtxt3 = Text(window, height = 1, width = 25, bg = "light yellow")
inputtxt3.pack()
inputtxt3.place(x=325, y=238)
Does this help you?
from tkinter import Tk, StringVar
from tkinter.ttk import Label, Combobox, Button
root = Tk()
def check(): # For checking the value of ComboBox
combo_value = var.get()
if combo_value == "Yes":
lbl.config(text="You selected 'Yes'")
else:
lbl.config(text="You selected 'No'")
var = StringVar() # To store the value of the Combobox
Combo = Combobox(root, values=["Yes", "No"], textvariable=var)
Combo.pack(pady=20)
btn = Button(root, text="Confirm", command=check)
btn.pack(pady=20)
lbl = Label(root)
lbl.pack(pady=20)
root.mainloop()

Python Tkinter mixing radio and default user input box in canvas?

I like to mixed my radio button selection with a few user input boxes.
I managed to output them separately but I can't combine them due to the one using canvas1.pack and another using row.pack.
This is my first radio button interface where user will select Auto or Manual and there is a box for user to input stock symbols manually.
This interface by default will show the default parameters such as volume or dividend amount and the user can change this parameter.
When I tried to put them together, they overlaps. The stock symbol input box was also shifted down. How can I move the parameter boxes below the auto and manual radio button without shifting the stock symbol box to the bottom?
Below is a sample of my code that is ready to be executed on jupyter.
from tkinter import *
from tkinter import simpledialog
from tkinter import messagebox
import tkinter as tk
#default filter values
parameter1 = 100000
parameter2 = 3
global answer
global user_list
# Prepare parameters
fields = ['Min. parameter1', 'Min. parameter2', 'Min. 3parameter3',
'Min. parameter4','Min. parameter5', 'Max. parameter6']
default_values = [parameter1,parameter2,parameter3,parameter4,
parameter5,parameter6]
captured_values = []
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
sys.stdout = orig_stdout
f.close()
sys.exit("Application closed by user")
def makeform(root, fields,default_values):
entries = {}
for i in range(len(fields)):
row = tk.Frame(root)
lab = tk.Label(row, width=24, text=fields[i]+": ", anchor='w')
ent = tk.Entry(row)
ent.insert(0, default_values[i])
row.pack(side=tk.TOP,
fill=tk.X,
padx=5,
pady=5)
lab.pack(side=tk.LEFT)
ent.pack(side=tk.RIGHT,
expand=tk.YES,
fill=tk.X)
entries[fields[i]] = ent
return entries
# Button click event
def btn_click (e):
global answer
answer_choice = rdo_var.get()
answer = rdo_txt[answer_choice]
global user_list
user_list = entry1.get()
captured_values.append(e['Min. parameter1'].get())
captured_values.append(e['Min. parameter2'].get())
captured_values.append(e['Min. parameter3'].get())
captured_values.append(e['Min. parameter4'].get())
captured_values.append(e['Min. parameter5'].get())
captured_values.append(e['Max. parameter6'].get())
root.destroy()
return answer
# Generate Tk class
root = tk.Tk()
# Screen size
root.geometry ('270x250')
# Screen title
root.title ('Enter parameters')
# set default parameters
ents = makeform(root, fields, default_values)
# box for manual input
canvas1 = tk.Canvas(root, width = 350, height = 400)
canvas1.pack()
entry1 = tk.Entry (root)
canvas1.create_window(165, 45, window=entry1)
# List radio button labels
rdo_txt = ['Auto','Manual']
# Radio button status
rdo_var = tk.IntVar ()
# Create and place radio buttons dynamically
for i in range (len (rdo_txt)):
rdo = Radiobutton (root, value = i, variable = rdo_var, text = rdo_txt [i])
rdo.place (x = 20, y = 15 + (i * 20))
# Create button
confirm_button = tk.Button (root, text = 'Confirm', command = (lambda e=ents: btn_click(e)))
confirm_button.place (x = 180, y = 200)
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop ()
if(answer == 'Manual'):
print('Manual run selected.')
manual_run = 1
temp_user_list = []
user_list = user_list.split(',')
for i in range(len(user_list)):
temp_user_list.append(user_list[i].strip().upper())
print('Symbol(s) entered : ' + str(temp_user_list))
else:
manual_run = 0
print('Auto run selected.')
# new captured values
parameter1 = float(captured_values[0])
parameter2 = float(captured_values[1])
Here is an expanded answer.
Complete code example.
from tkinter import *
from tkinter import simpledialog
from tkinter import messagebox
import tkinter as tk
#default filter values
parameter1 = 100000
parameter2 = 2
parameter3 = 3
parameter4 = 4
parameter5 = 5
parameter6 = 6
global answer
global user_list
# Prepare parameters
fields = ['Min. parameter1', 'Min. parameter2', 'Min. parameter3',
'Min. parameter4','Min. parameter5', 'Max. parameter6']
default_values = [parameter1,parameter2,parameter3,parameter4,
parameter5,parameter6]
captured_values = []
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
sys.stdout = orig_stdout
f.close()
sys.exit("Application closed by user")
def makeform(root, fields,default_values):
entries = {}
for i in range(len(fields)):
row = tk.Frame(root)
lab = tk.Label(row, width=28, text=fields[i]+": ", anchor='e')
ent = tk.Entry(row)
ent.insert(0, default_values[i])
row.pack(side=tk.TOP,
fill=tk.X,
padx=5,
pady=5)
lab.pack(side=tk.LEFT)
ent.pack(side=tk.RIGHT,
expand=tk.YES,
fill=tk.X)
entries[fields[i]] = ent
return entries
# Button click event
def btn_click (e):
global answer
answer_choice = rdo_var.get()
answer = rdo_txt[answer_choice]
global user_list
user_list = entry1.get()
captured_values.append(e['Min. parameter1'].get())
captured_values.append(e['Min. parameter2'].get())
captured_values.append(e['Min. parameter3'].get())
captured_values.append(e['Min. parameter4'].get())
captured_values.append(e['Min. parameter5'].get())
captured_values.append(e['Max. parameter6'].get())
root.destroy()
return answer
# Generate Tk class
root = tk.Tk()
# Screen size
root.geometry("410x260")
# Screen title
root.title('Enter parameters')
# set default parameters
ents = makeform(root, fields, default_values)
# box for manual input
manual = makeform(root, ['Manual input'], ["Enter value here"])
entry1 = manual["Manual input"]
entry1["background"] = "yellow" # make it standout
del manual
# List radio button labels
rdo_txt = ['Auto','Manual']
# Radio button status
rdo_var = tk.IntVar()
# Create and place radio buttons dynamically
for i in range (len (rdo_txt)):
rdo = Radiobutton (root, value = i, variable = rdo_var, text = rdo_txt [i])
rdo.place (x = 20, y = 15 + (i * 20))
# Create button
confirm_button = tk.Button (root, text = 'Confirm', command = (lambda e=ents: btn_click(e)))
confirm_button.place (x = 205, y = 220)
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
if(answer == 'Manual'):
print('Manual run selected.')
manual_run = 1
temp_user_list = []
user_list = user_list.split(',')
for i in range(len(user_list)):
temp_user_list.append(user_list[i].strip().upper())
print('Symbol(s) entered : ' + str(temp_user_list))
else:
manual_run = 0
print('Auto run selected.')
# new captured values
parameter1 = float(captured_values[0])
parameter2 = float(captured_values[1])

TypeError: 'Entry' object cannot be interpreted as an integer

from tkinter import ttk, simpledialog
import tkinter as tk
from tkinter import *
root = Tk()
root.resizable(0, 0)
root.title("Sorting and Searching Algorithm")
root.configure(bg='#ff8080')
root.geometry("750x550")
def arrays():
v = IntVar()
for widget in root.winfo_children():
widget.destroy()
def close():
for widget in root.winfo_children():
widget.destroy()
arrays()
titleFrame = Frame(root)
titleFrame.grid(row=0)
radioFrame = Frame(root)
radioFrame.grid(padx=350, pady=100)
inputFrame = tk.Frame(root, bg='#ff8080')
inputFrame.grid()
buttonFrame = Frame(root)
buttonFrame.grid()
Title = tk.Label(titleFrame, bg='#ff8080', text="Enter The Number of Elements In The Array", font="-weight bold")
Title.grid()
global NUMBER_OF_ENTRIES
NUMBER_OF_ENTRIES = Entry(inputFrame)
NUMBER_OF_ENTRIES.grid(row=0, column=1, sticky=E, ipadx=10, ipady=10,padx=10, pady=10)
if NUMBER_OF_ENTRIES == int:
print("Working")
else:
print("Please Enter a Integer Value")
global num
num = 0
#global NUMBER_OF_ENTRIES
#NUMBER_OF_ENTRIES = simpledialog.askinteger("Please Enter", "Enter The Number of Elements In The Array")
global alist
alist = []
for i in range (0, NUMBER_OF_ENTRIES):
num = simpledialog.askinteger("Please Enter" ,"Enter The Entries In Array Element " + str(i))
alist = alist + [ num ]
calculate = ttk.Button(buttonFrame, text="Proceed", command=entries)
calculate.grid(row=4, column=0, sticky=E + S, ipadx=10, ipady=10)
arrays()
root.mainloop()
I am trying to make it so when a user inputs a integer number into the Entry input box it stores into the variable NUMBER_OF_ENTRIES. After it stores it, it then proceeds to use the value in the further conditionals.
But I am getting an issue when I try to compile it.
Because it's not an integer. NUMBER_OF_ENTRIES is of type <class 'tkinter.Entry'>.
The usual way to do this is to associate the entry with a StringVar() which will reflect whatever is typed into the entry.
The text entered into an entry is still text so you'll have to convert it to int explicitly.
See The Tkinter Entry Widget.

tkinter: dynamically create and delete entry

I am using tkinter to create a small GUI for some Python scripts. For this GUI I need a Combobox named combo with three options:
"none" (the user wants to hand in no data)
"constant" (the user wants to hand in only one value)
"adjustable" (the user wants to hand in more than one value)
Depending on the choice done in combo, a different number of entrys should
appear. The first option should show no entry (and delete all "leftover"
entrys), the second one should show only one entry and the third one should show
two entrys. For me it's no problem to create these entrys but I don't know how
to make them disappear. Once they were created they stay until the GUI is
closed.
I tried something like this:
import tkinter as tk
master = tk.Tk()
var1 = tk.StringVar()
var2 = tk.StringVar()
def submit():
if choice.get() == "none": # all entry boxes schould disappear
entry1.destroy()
entry2.destroy()
if choice.get() == "constant": # only 1 entry box schould be visible
entry1 = tk.Entry(master, textvariable = var1)
entry1.grid(column = 0, row = 1)
entry2.destroy()
if choice.get() == "adjustable": # all entry boxes should be visible
entry1 = tk.Entry(master, textvariable = var1)
entry1.grid(column = 0, row = 1)
entry2 = tk.Entry(master, textvariable = var1)
entry2.grid(column = 0, row = 2)
choice = tk.StringVar(value = "none")
combo = ttk.Combobox(master, textvariable = choice, state = "readonly")
combo["values"] = ("none", "constant", "adjustable")
combo.grid(column = 0, row = 0)
action = tk.Button(master, text = "confirm", command = submit)
action.grid(column=1, row=0)
master.mainloop()
But as I said before, once a entry was created it did not disappear anymore. I
also tried entry.grid_forget() insted of entry.destroy() but this also
didn't work.
I also tryed to declare entry1 and entry1 outside of submit() but then I
don't know how to recreate these entrys once they were destroyed.
Thanks to the help of jasonharper I found a solution while working at another script. The code should look something like this:
import tkinter as tk
from tkinter import ttk
master = tk.Tk()
var1 = tk.StringVar()
var2 = tk.StringVar()
def submit():
if choice.get() == "none": # all entry boxes schould disappear
entry1.grid_remove()
entry2.grid_remove()
if choice.get() == "constant": # only 1 entry box schould be visible
entry1.grid(column = 0, row = 1)
entry2.grid_remove()
if choice.get() == "adjustable": # all entry boxes should be visible
entry1.grid(column = 0, row = 1)
entry2.grid(column = 0, row = 2)
choice = tk.StringVar(value = "none")
combo = ttk.Combobox(master, textvariable = choice, state = "readonly")
combo["values"] = ("none", "constant", "adjustable")
combo.grid(column = 0, row = 0)
entry1 = tk.Entry(master, textvariable = var1)
entry2 = tk.Entry(master, textvariable = var2)
action = tk.Button(master, text = "confirm", command = submit)
action.grid(column=1, row=0)
master.mainloop()
Now all entrys are deleted or created when wanted. To delete the text at the entrys You only have to add entry.delete(0,"end").
I hope this will also help others.

Change (update) text in Python Tkinter widgets

I am trying to update information in tkinter labels and buttons without redrawing entire screens. I'm using Python 3, a Raspberry Pi, and Idle. I have a trivial example of what I am trying to do. I see comments here that suggest I need to learn to manipulate stringvariable or IntVar, etc. but my book is totally unhelpful in that regard. In this example, I would like the number between the buttons to track the value of the number as it changes with button pushes.
##MoreOrLess.01.py
from tkinter import *
global number
number = 5
root = Tk()
root.title("Test Buttons")
def Less():
global number
number -= 1
print ("The number is now ", number)
def More():
global number
number += 1
print("The number is now ", number)
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, text = number).pack(pady = 20)
MakeLabel(number)
Not only do you base yourself in a book, check the official documentation of tkinter. in your case you must create a variable of type IntVar with its set() and get() method, and when you want to link that variable through textvariable.
from tkinter import *
root = Tk()
root.title("Test Buttons")
number = IntVar()
number.set(5)
def Less():
number.set(number.get() - 1)
print ("The number is now ", number.get())
def More():
number.set(number.get() + 1)
print("The number is now ", number.get())
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, textvariable = number).pack(pady = 20)
MakeLabel(number)
root.mainloop()

Categories