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
Related
hi i am making a code using tkinter that has button and i want it to do different thing is the button is pressed.
import tkinter as tk
Height = 500
Width = 700
def comp():
if ? == ?:
print("hi")
elif ? == ?:
print("bye")
elif ? == ?:
print("trump")
elif ? == ?:
print("bidden")
window = tk.Tk()
canvas = tk.Canvas(window, height=Height, width=Width)
canvas.pack()
frame = tk.Frame(window)
frame.place(relx=0,rely=0, relheight=1, relwidth=1)
label = tk.Label(frame, text="hello malcom what would you like to do?")
label.place(relx=0.3, rely=0, relwidth=0.45, relheight=0.20)
button = tk.Button(frame, text="add someone new", bg='black', fg='white', command=comp)
button.place(relx=0.3, rely=0.2, relwidth=0.45, relheight=0.10)
button1 = tk.Button(frame, text="register a visit", bg='black', fg='white', command=comp)
button1.place(relx=0.3, rely=0.4, relwidth=0.45, relheight=0.10)
button2 = tk.Button(frame, text="view data", bg='black', fg='white', command=comp)
button2.place(relx=0.3, rely=0.6, relwidth=0.45, relheight=0.10)
button3 = tk.Button(frame, text="end program", bg='black', fg='white', command=comp)
button3.place(relx=0.3, rely=0.8, relwidth=0.45, relheight=0.10)
window.mainloop()
as you can see i have the buttons on a frame and i need it to do specific things dependat on what was pressed
please can someone advise on what to do?
I am trying to create a python program to create the code for another python program. i have been learning python over the past week using a book (learn python in 24 hrs by katie cunningham) and also numerous online sources. i have run into a problem with the OptionMenu in tkinter where, it does not show the selected option or the default option (i used variable.set("defaultvalue")). i know that the program might be very inefficient, so please go easy on me. also if i dont provide option.config(width="14") the widget stays small.(please see the var_create_fn() function)
ive tried reinstalling pycharm and also python.
from tkinter import *
# from PIL import Image,ImageTk
from tkinter.messagebox import showinfo
window = Tk()
window.geometry('650x520')
window.title("Sash's CodeBuilder (feat.Python)")
main_label = Label(window, text="CodeBuilder Alpha", fg="indigo", bg="white", relief=SOLID, font=("arial", 30, "bold", "italic"))
main_label.pack(fill=BOTH, padx=3, pady=3)
# Variable declarations
printable = StringVar()
variable = StringVar()
varVal = StringVar()
varTypeSet = StringVar()
varTypes = ["String", "Integer"]
dataTypes = ["int", "float", "String", "list", "eval"]
dataTypeSet = StringVar()
inText = StringVar()
inVar = StringVar()
forVar = StringVar()
forPar = StringVar()
rangeChk = IntVar()
# FUNCTIONS
def printer():
showinfo(title="Printer", message="Printed.")
code = open("D:\\file.py", "a")
code.write("print(" + printable.get() + ")") & code.write("\n")
def var_create_fn():
window2 = Tk()
window2.geometry('150x100')
window2.title("Data Type Select")
window2_label = Label(window2, text="Select a data type :", bg="white", relief=SOLID, font=("arial", 10))
window2_label.pack(fill=BOTH, padx=3, pady=3)
var_data_type_box = OptionMenu(window2, varTypeSet, *varTypes)
var_data_type_box.config(width="14")
varTypeSet.set("select data type")
var_data_type_box.place(x=10, y=30)
but = Button(window2, text="Print", command=var_create_sub, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
but.place(x=55, y=70)
window2.mainloop()
def var_create():
if varVal.get() == "Enter variable value":
var_create_fn()
else:
showinfo(title="Variable creation", message="Variable with specified value created")
code = open("D:\\file.py", "a")
code.write(variable.get() + "=" + varVal.get()) & code.write("\n")
def var_create_sub():
global var1
var1 = varTypeSet.get()
if var1 == "String":
showinfo(title="Variable creation", message="Variable with specified value created")
code = open("D:\\file.py", "a")
code.write(variable.get() + " = StringVar()") & code.write("\n")
elif var1 == "Integer":
showinfo(title="Variable creation", message="Variable with specified value created")
code = open("D:\\file.py", "a")
code.write(variable.get() + " = IntVar()") & code.write("\n")
exit()
else:
showinfo(title="Variable creation", message="please select a value :")
def in_create():
create_data_type = dataTypeSet.get()
if create_data_type == "Select Data type":
showinfo(title="error", message="Empty field")
elif create_data_type != "String":
showinfo(title="Input creation", message="Input Code,, with specified data type and variable created")
code = open("D:\\file.py", "a")
code.write(inVar.get() + "=" + create_data_type+'(input("'+inText.get()+'"))') & code.write("\n")
else:
showinfo(title="Input creation", message="Input Code,, with specified data type and variable created")
code = open("D:\\file.py", "a")
code.write(inVar.get() + '=input("' + inText.get() + '")') & code.write("\n")
def for_create():
showinfo(title="For loop created", message="For loop with specified variable and parameters created.")
if rangeChk.get() == 1:
code = open("D:\\file.py", "a")
code.write("for " + forVar.get() + " in range(" + forPar.get() + "):") & code.write("\n")
else:
code = open("D:\\file.py", "a")
code.write("for " + forVar.get() + " in " + forPar.get() + ":") & code.write("\n")
# PROGRAM EXIT
btx = Button(window, text="Exit", command=exit, relief=SOLID, font=("arial", 14, "bold"))
btx.place(x=300, y=470)
# FOR PRINTING SOMETHING
# print label
printLabel = Label(window, text="Enter text to print :", bg="white", relief=SOLID, font=("arial", 10))
printLabel.place(x=5, y=58)
# text box
printBox = Entry(window, textvar=printable)
printBox.place(x=124, y=60)
# Print button
bt1 = Button(window, text="Print", command=printer, relief=RIDGE, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
bt1.place(x=250, y=57)
# CREATING A VARIABLE
# Variable label
varLabel = Label(window, text="Create a variable :", bg="white", relief=SOLID, font=("arial", 10))
varLabel.place(x=5, y=84)
# Variable Box
varBox = Entry(window, textvar=variable)
varBox.insert(END, "Enter variable name")
varBox.place(x=124, y=87)
# Variable value box
varValBox = Entry(window, textvar=varVal)
varValBox.insert(0, "Enter variable value")
varValBox.place(x=254, y=87)
# Variable Button
bt2 = Button(window, text="Create", relief=RIDGE, command=var_create, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
bt2.place(x=380, y=82)
# CREATING INPUT CODE
# Input label
inLabel = Label(window, text="Create input Code:", bg="white", relief=SOLID, font=("arial", 10))
inLabel.place(x=5, y=110)
# Data type combo box
inDataType = OptionMenu(window, dataTypeSet, *dataTypes)
dataTypeSet.set("Select Data type")
inDataType.config(width="14")
inDataType.place(x=122, y=107)
# Input text box
inTextBox = Entry(window, textvar=inText)
inTextBox.insert(0, "Enter input text")
inTextBox.place(x=254, y=113)
# Input variable box
inVarBox = Entry(window, textvar=inVar)
inVarBox.insert(0, "Enter input variable")
inVarBox.place(x=382, y=113)
# Input Button
b3 = Button(window, text="Create", relief=RIDGE, command=in_create, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
b3.place(x=508, y=110)
# FOR LOOP
# For Loop label
forLabel = Label(window, text=" Create For loop:", bg="white", relief=SOLID, font=("arial", 10))
forLabel.place(x=5, y=136)
# For Variable box
forVarBox = Entry(window, textvar=forVar)
forVarBox.insert(0, "Enter loop variable")
forVarBox.place(x=124, y=139)
# For Loop parameters box
forParBox = Entry(window, textvar=forPar)
forParBox.insert(0, "Enter loop parameters")
forParBox.place(x=254, y=139)
# for Button
b4 = Button(window, text="Create", relief=RIDGE, bg="#44ff4c", fg="Blue", command=for_create, font=("arial", 9, "bold"))
b4.place(x=382, y=136)
# range check box
rangeChkBut = Checkbutton(window, text="use range", onvalue=1, offvalue=0, variable=rangeChk)
rangeChkBut.place(x=442, y=138)
window.mainloop()
You should not use Tk() to create the dialog window. See Why are multiple instances of Tk discouraged?.
Use Toplevel() instead:
def var_create_fn():
window2 = Toplevel(window)
...
Update
Your program suggests that you are familiar with Python but may need help with Tkinter I suggest you look at Where to learn tkinter for Python?.
For python in general I suggest you search for Python exercises and try out a few until you find one that suits your level. I do, however, recommend Python 3 Module of the Week.
I have a button that when clicked displays slider / scale. How to get the selected value from slider?
My code returns error: "TypeError: funcSlider() missing 1 required positional argument: 'value'"
self.list = {}
def onClick(self):
print (self.list)
return
def funcSlider(self, posX,posY,key,value):
w = tk.Scale(self, from_=0, to=8, orient='horizontal')
w.pack()
w.place(x=posX, y=posY, in_=self)
self.list [key] = value
button = tk.Button(self, text="button ",
command=lambda: self.funcSlider(120,33,'test'),width = 20)
button .pack(anchor="w")
button .place(x=250, y=50, in_=self)
button2 = tk.Button(self, text="Send",
command=self.onClick, width=42,bg="#4BAD2E")
button2 .pack(anchor="w")
button2 .place(x=250, y=430, in_=self)
I think I did it. I do not know if it is a 'good practice', but it works :D
self.list = {}
def foo(self,x,key):
self.list [key] = x
def onClick(self):
print (self.list)
return
def funcSlider(self, posX,posY,key):
w = tk.Scale(self, from_=0, to=8, orient='horizontal',command=lambda s: self.foo(s,key))
w.pack()
w.place(x=posX, y=posY, in_=self)
self.list [key] = value
button = tk.Button(self, text="button ",
command=lambda: self.funcSlider(120,33,'test'),width = 20)
button .pack(anchor="w")
button .place(x=250, y=50, in_=self)
button2 = tk.Button(self, text="Send",
command=self.onClick, width=42,bg="#4BAD2E")
button2 .pack(anchor="w")
button2 .place(x=250, y=430, in_=self)
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()
I have rewrote the example shown in this link!
The code is shown here:
from tkinter import *
def sel():
if var.get()==1:
area.delete(1.0, END)
area.insert(END, "Bienvenue")
elif var.get()==2:
area.delete(1.0, END)
area.insert(END, "Welcome")
else:
selection = "You selected the option " + str(var.get())
label.config(text = selection)
area.delete(1.0, END)
area.insert(END,selection)
root = Tk()
area = Text(root)
area.pack()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack(anchor=W)
R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
command=sel)
R2.pack(anchor=W)
R3 = Radiobutton(root, text="Option 3", variable=var, value=3,
command=sel)
R3.pack(anchor=W)
label = Label(root)
label.pack()
root.mainloop()
Like this, the code will enter a message in the text widget, following the radiobutton value.
Example: if option1 is chosed, i will have the message "bienvenue" in the text widget.
But when i wanted to put this code in a class object, i couldn't have the same result; here is the code:
from tkinter import *
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
""" La fenétre principale"""
self.parent.title("Agent")
self.pack(fill=BOTH, expand=1)
area = Text(m1)
area.pack()
global var
var = IntVar()
R1 = Radiobutton(m1, text="Option 1", variable=var, value=1,
command=self.sel(area))
R1.pack(anchor=W)
R2 = Radiobutton(m1, text="Option 2", variable=var, value=2,
command=self.sel(area))
R2.pack(anchor=W)
R3 = Radiobutton(m1, text="Option 3", variable=var, value=3,
command=self.sel(area))
R3.pack(anchor=W)
label = Label(self)
label.pack()
def sel(self,area):
if var.get()==1:
area.delete(1.0, END)
area.insert(END, "Bienvenue")
elif var.get()==2:
area.delete(1.0, END)
area.insert(END, "Welcome")
else:
selection = "You selected the option " + str(var.get())
#label.config(text = selection)
area.delete(1.0, END)
area.insert(END,selection)
def main():
root = Tk()
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
I am not sure what i did wrongly when i used the class object. So could you please help me figure it out.
The problem is in this line (and similar for the other two buttons):
R2 = Radiobutton(m1, text="Option 2", variable=var, value=2,
command=self.sel(area))
By doing command=self.sel(area), you set command to the result of executing self.sel(area), which is None, instead of the method self.sel itself.
Instead, I suggest changing area to self.area in all of your code and removing the additional parameter from the sel method.
def initUI(self):
...
self.area = Text(m1)
...
R1 = Radiobutton(m1, text="Option 1", variable=var, value=1,
command=self.sel)
...
def sel(self):
if var.get()==1:
self.area.delete(1.0, END)
...
...