I have an OptionMenu, and I want that when one of its options is selected a widget is displayed.
For example
...
var = StringVar()
w = OptionMenu(root, var, "apple", "orange", "grapes")
w.grid(column=1, row=1)
w.config(width=15)
var.set(" ")
Now, if I select "apple", then it should display a label or a button saying "apples are red".
I think this might be what you're after
import tkinter as tk
def toggle(item):
#Destorys all existing widgets in frame
for wid in wid_frame.winfo_children():
wid.destroy()
#Packs the selected widget
if item == 'Label':
tk.Label(wid_frame, text='Hello World!').pack()
elif item == 'Button':
tk.Button(wid_frame, text='Hello World!').pack()
elif item == 'Entry':
tk.Entry(wid_frame).pack()
root = tk.Tk()
var = tk.StringVar()
var.set("Pick Widget")
op_menu = tk.OptionMenu(root, var, "None", "Label", "Button", "Entry", command=toggle)
op_menu.pack()
op_menu.config(width=15)
wid_frame = tk.Frame(root)
wid_frame.pack()
root.mainloop()
Related
I want to define a row of tk checkbox widget looping on a list of labels. Everything works fine except that I can't seem to be able to set the IntVar value on the if statement, although it works for the state. What am I doing wrong?
def CheckboxLine(self, frame, fformat=None):
self.__set_col(0) # set widget column to zero
var_c = []
widget_c = []
if fformat is None:
fformat = ['text', 'excel', 'xml']
# widget definition
for item in fformat:
var_c.append(tk.IntVar(master=frame))
widget_c.append(tk.Checkbutton(master=frame, text=item, variable=var_c[-1]))
if item == 'text':
var_c[-1].set(1)
widget_c[-1]['state']='disabled'
else:
var_c[-1].set(0)
widget_c[-1]['state']='normal'
widget_c[-1].grid(row=self.__row, column=self.__col, columnspan=1, padx=self.__padx, pady=self.__pady, sticky="nsew")
self.__next_col()
self.__next_row()
Define var_c and widget_c outside of your function. The reason behind this is unclear to me, unfortunately.
import tkinter as tk
root = tk.Tk()
var_c = []
widget_c = []
def CheckboxLine(frame, fformat=None):
if fformat is None:
fformat = ['text', 'excel', 'xml']
# widget definition
for idx, item in enumerate(fformat):
var_c.append(tk.IntVar(value=0))
widget_c.append(tk.Checkbutton(master=frame, text=item, variable=var_c[-1]))
if item == "text":
var_c[-1].set(1)
widget_c[-1]["state"] = "disabled"
widget_c[-1].grid(row=idx, column=0)
CheckboxLine(root)
root.mainloop()
I am trying to make a simple app in Tkinter but I ran into a problem. I am trying to use the value that is defined with a Radio Button in a function, but it doesn't seem to work. When I press the Button nothing is printed. What am I doing wrong?
from tkinter import *
window = Tk()
window.title("ALL YOU NEED IS EXCEL")
window.geometry('500x200')
variable_1 = StringVar()
rad1 = Radiobutton(window,text='Button 1', value= "Button 1", variable= variable_1)
rad1.grid(column=0, row=4)
rad2 = Radiobutton(window,text='Button 2', value= "Button 2",variable= variable_1)
rad2.grid(column=1, row=4)
def clicked(vrijednost):
if vrijednost == "Button 1":
print("This is Button 1")
if vrijednost == "Button 2":
print("This is Button 2")
btn = Button(window, text="PRINT", height = 2,width = 15, command=clicked(variable_1))
#btn.grid(column=1, row=5)
btn.place(x = 250, y = 150)
window.mainloop()
Instead of passing the value in the function, you can use vrijednost = variable_1.get() inside the function body itself.
Try the following code:
from tkinter import *
window = Tk()
window.title("ALL YOU NEED IS EXCEL")
window.geometry('500x200')
variable_1 = StringVar()
rad1 = Radiobutton(window,text='Button 1', value= "Button 1", variable= variable_1)
rad1.grid(column=0, row=4)
rad2 = Radiobutton(window,text='Button 2', value= "Button 2",variable= variable_1)
rad2.grid(column=1, row=4)
def clicked():
vrijednost = variable_1.get()
if vrijednost == "Button 1":
print("This is Button 1")
if vrijednost == "Button 2":
print("This is Button 2")
btn = Button(window, text="PRINT", height = 2,width = 15, command=clicked)
#btn.grid(column=1, row=5)
btn.place(x = 250, y = 150)
window.mainloop()
Edit: Adding StringVar() parameter.
However, using walrus operator this can be done quite easily.
code:
from tkinter import *
window = Tk()
window.title("ALL YOU NEED IS EXCEL")
window.geometry('500x200')
variable_1 = StringVar(window, '1')
rad1 = Radiobutton(window,text='Button 1', value= "Button 1", variable= variable_1)
rad1.grid(column=0, row=4)
rad2 = Radiobutton(window,text='Button 2', value= "Button 2",variable= variable_1)
rad2.grid(column=1, row=4)
def clicked():
if (vrijednost := variable_1.get()) == "Button 1":
print("This is Button 1")
else:
print("This is Button 2")
btn = Button(window, text="PRINT", height = 2,width = 15, command=clicked)
btn.place(x = 250, y = 150)
window.mainloop()
Output image:
Output radiobutton2
I would like to use Tkinter to be able to disable one entry if 'no' is selected from a drop down menu.
from tkinter import *
def disableEntry(entry):
entry.config(state='disable')
def allowEntry(entry):
entry.config(state='normal')
def main():
print("test")
root = Tk() #create a TK root window
root.title("Lunch and Learn") #Title of the window
L1 = Label(root, text = "Label 1").grid(row=0, column=0, padx=30, pady=(20,5))
L2 = Label(root, text = "Label 2").grid(row=1, column=0, pady=5)
var = StringVar()
E1 = Entry(root,bd =3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root,var,"yes","no")
D1.grid(row=1,column=1)
if var.get() == 'no':
disableEntry(E1)
elif var.get() == 'yes':
allowEntry(E1)
B2 = Button(text = "Submit", command=main).grid(row=4, column=2)
root.mainloop()
the above code is a simple example of what i have tried. I have created two functions called 'disableEntry' and 'allowEntry' which should change the state of the entry box but they don't appear to do anything when i change the input of the drop down menu.
i dont know if i am approaching this the wrong way or if there is a standardized way to do this.
any help would be appreciated.
You need a way to check the state of the selection after it is changed. That can be achieved with adding a callback command to the OptionMenu widget.
You were checking the correct variable, but the point you were checking it at was before the screen window had even displayed.
from tkinter import Label, StringVar, OptionMenu, Entry, Tk, Button
# change the state of the Entry widget
def change_state(state='normal'):
E1.config(state=state)
def main():
print("test")
# callback function triggered by selecting from OptionMenu widget
def callback(*args):
if var.get() == 'no':
change_state(state='disable')
elif var.get() == 'yes':
change_state(state='normal')
root = Tk() #create a TK root window
root.title("Lunch and Learn") #Title of the window
L1 = Label(root, text="Label 1").grid(row=0, column=0, padx=30, pady=(20, 5))
L2 = Label(root, text="Label 2").grid(row=1, column=0, pady=5)
var = StringVar()
E1 = Entry(root, bd=3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root, var, "yes", "no", command=callback)
D1.grid(row=1, column=1)
B2 = Button(text = "Submit", command=main).grid(row=4, column=2)
root.mainloop()
I don't have any idea how to make a buttons that output an integer.
This is a cash register system, everytime the user click that button the price should automatically sums up in the total, and automatically minus and show up a change.
from tkinter import *
from tkinter.font import Font
class MainUI:
def __init__(self,master):
#MAIN WINDOW
self.mainFrame = Frame(master, width=800, height=600,
bg="skyblue")
master.title("FCPC CASH REGISTER")
self.mainFrame.pack()
self.title = Label(self.mainFrame, text="FIRST CITY PROVIDENTIAL"
" COLLEGE", bg="blue")
self.font = Font(family="Helvetica", size=29)
self.title.configure(font=self.font)
self.title.place(x=50, y=50)
#BUTTONS
self.snacksButton = Button(self.mainFrame, text="SNACKS",
command=self.snackList, width=10, bg="blue")
self.font = Font(family="Helvetica", size=20)
self.snacksButton.configure(font=self.font)
self.snacksButton.place(x=100,y=150,)
#TOTAL
self.total = Label(self.mainFrame,text="TOTAL:",
bg="blue",width=8)
self.total.place(x=370,y=160)
self.font = Font(family="Helvetica", size=25)
self.total.configure(font=self.font)
#CHANGE
self.change = Label(self.mainFrame,text="CHANGE:", bg="blue")
self.change.place(x=370,y=240)
self.font = Font(family="Helvetica", size=25)
self.change.configure(font=self.font)
def snackList(self):
self.frame = Toplevel(width=800,height=600,bg="skyblue")
self.frame.title("SNACKS")
self.novaButton = Button(self.frame, text="NOVA(12php)",
command=self.calculate ,width=15, bg="blue")
self.font = Font(family="Helvetica", size=15)
self.novaButton.configure(font=self.font)
self.novaButton.place(x=100,y=150)
root = Tk()
ui = MainUI(root)
root.mainloop()
I want the button to output the price and automatically calculates the total amount.
I've put together a simple example to illustrate what you might need to do. Associate each button to a function that adds the price of a snack to the total amount and changes what is displayed. One way to do it is with a textvariable option of tkinter Label widget.
Example:
import tkinter as tk
def calculate(price):
global total, var
total += price
text = 'Total = ' + str(total)
var.set(text)
root = tk.Tk()
total = 0
var = tk.StringVar()
button1 = tk.Button(root, text='Snickers 1$', command=lambda: calculate(price=1)).pack()
button2 = tk.Button(root, text='Mars 2$', command=lambda: calculate(price=2)).pack()
totalLabel = tk.Label(root, textvariable=var).pack()
root.mainloop()
I am trying to set the value of one checkbox to always be the opposite of the other using tkinter (python3.5). I want it to be so that when ever the user click on one of the Checkbuttons, the other button is always changed to the opposite value.
What am I doing wrong? I cant work it out.
from tkinter import *
def opposite(buttonA):
print("running Opposite")
if buttonA.get() == 0:
buttonB.set(1)
elif buttonA.get() == 1:
buttonB.set(0)
root = Tk()
buttonA=IntVar()
buttonA.set(1)
buttonAchk = Checkbutton(root, variable=buttonA)
buttonAchk.pack()
buttonAlabel = Label(root, width=30, text="Button A")
buttonAlabel.pack()
buttonB=IntVar()
buttonB.set(0)
buttonBCheck = Checkbutton(root, variable=opposite(buttonA))
buttonBCheck.pack()
buttonBlabel = Label(root, width=30, text="Button B")
buttonBlabel.pack()
root.mainloop()
Maybe use, Radiobutton instead?
from tkinter import *
root = Tk()
buttonA=IntVar()
R1 = Radiobutton(root, text="Button A", width = 30, variable=buttonA, value=1)
R1.pack()
R2 = Radiobutton(root, text="Button B", width = 30, variable=buttonA, value=0)
R2.pack()
root.mainloop()