python tkinter resizing of images - python

hi i am trying to resize images together with buttons on a grid whenever program window is resized,most of the guides just teach how to resize buttons but buttons or text inside of them stays the same .i think that this is possible with pack() but not sure and would like to know if its possible with grid.
thanks for your time.
from tkinter import *
import math
# ----- calculator class
class calc:
def getandreplace(self):
# replaces x with * and ÷ with /
self.expression = self.e.get()
self.newtext=self.expression.replace("/","/")
self.newtext=self.newtext.replace("x","*")
def equals(self):
# when = button is pressed
self.getandreplace()
try:
# evaluates expresion with eval command
self.value = eval(self.newtext)
except SyntaxError or NameError or ZeroDivisionError:
self.e.delete(0,END)
self.e.insert(0,"Invalid input!")
else:
self.e.delete(0,END)
self.e.insert(0,self.value)
def squareroot(self):
# square root
self.getandreplace()
try:
# evaluates expresion with eval command
self.value = eval(self.newtext)
except SyntaxError or NameError:
self.e.delete(0, END)
self.e.insert(0, "Invalid input!")
else:
self.sqrtval=math.sqrt(self.value)
self.e.delete(0,END)
self.e.insert(0,self.sqrtval)
def square(self):
# square
self.getandreplace()
try:
# evaluates expresion with eval command
self.value = eval(self.newtext)
except SyntaxError or NameError:
self.e.delete(0, END)
self.e.insert(0, "Invalid input!")
else:
self.sqval=math.pow(self.value,2)
self.e.delete(0,END)
self.e.insert(0,self.sqval)
def clearall(self):
# function to clear input from screen
self.e.delete(0,END)
def clear1(self):
self.txt=self.e.get()[:-1]
self.e.delete(0,END)
self.e.insert(0,self.txt)
def action(self,argi):
# when presing button,value typed will be inserted into end of text area
self.e.insert(END,argi)
def __init__(self,master):
# constructor
for x in range(6):
for y in range(4):
Grid.columnconfigure(master, x, weight=1)
Grid.rowconfigure(master, y, weight=1)
master.title("Calculator")
master.geometry('500x500')
master.iconbitmap(r'number_5.ico')
master.minsize(300,370)
self.e = Entry(master,font=20)
self.e.grid(row=0,column=0,columnspan=6,pady=16, sticky=N+S+E+W)
self.e.focus_set() # sets focus to input text area
# makes buttons
Button(master,text="=",width=11,height=3,font=("Helvetica", 15),fg="black",
bg="white",command=lambda:self.equals()).grid(
row=4, column=4,columnspan=2, sticky=N+S+E+W)
Button(master, text="cl_all",width=5,height=3,font=("Helvetica", 15),
fg="red", bg = "light green",
command=lambda:self.clearall()).grid(row=1, column=4, sticky=N+S+E+W)
Button(master, text="cl_one", width=5, height=3,font=("Helvetica", 15),
fg="red", bg="light green",
command=lambda: self.clear1()).grid(row=1, column=5, sticky=N+S+E+W)
Button(master, text="+", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="white",
command=lambda: self.action("+")).grid(row=4, column=3, sticky=N+S+E+W)
Button(master, text="x", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="white",
command=lambda: self.action("x")).grid(row=2, column=3, sticky=N+S+E+W)
Button(master, text="-", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="white",
command=lambda: self.action("-")).grid(row=3, column=3, sticky=N+S+E+W)
Button(master, text="÷", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="white",
command=lambda: self.action("/")).grid(row=1, column=3, sticky=N+S+E+W)
Button(master, text="%", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="white",
command=lambda: self.action("%")).grid(row=4, column=2, sticky=N+S+E+W)
Button(master, text="7", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("7")).grid(row=1, column=0, sticky=N+S+E+W)
Button(master, text="8", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("8")).grid(row=1, column=1, sticky=N+S+E+W)
Button(master, text="9", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("9")).grid(row=1, column=2, sticky=N+S+E+W)
Button(master, text="4", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("4")).grid(row=2, column=0, sticky=N+S+E+W)
photo = PhotoImage(file='number_5.png')
label_photo = Label(master, image=photo)
label_photo.photo = photo
label_photo.grid(column=1, row=2, sticky=N+S+E+W)
Button(master, image=photo, width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("5")).grid( pady=2, padx=2, row=2, column=1, sticky=N+S+E+W)
Button(master, text="6", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("6")).grid(row=2, column=2, sticky=N+S+E+W)
Button(master, text="1", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("1")).grid(row=3, column=0, sticky=N+S+E+W)
Button(master, text="2", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("2")).grid(row=3, column=1, sticky=N+S+E+W)
Button(master, text="3", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action("3")).grid(row=3, column=2, sticky=N+S+E+W)
Button(master, text="0", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="light blue",
command=lambda: self.action(0)).grid(row=4, column=0, sticky=N+S+E+W)
Button(master, text=".", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="azure3",
command=lambda: self.action(".")).grid(row=4, column=1, sticky=N+S+E+W)
Button(master, text="(", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="azure3",
command=lambda: self.action("(")).grid(row=2, column=4, sticky=N+S+E+W)
Button(master, text=")", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="azure3",
command=lambda: self.action(")")).grid(row=2, column=5, sticky=N+S+E+W)
Button(master, text="S_root", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="azure3",
command=lambda: self.squareroot()).grid(row=3, column=4, sticky=N+S+E+W)
Button(master, text="x²", width=5, height=3,font=("Helvetica", 15),
fg="black", bg="azure3",
command=lambda: self.square()).grid(row=3, column=5, sticky=N+S+E+W)
window = Tk()
obj = calc(window)
window.mainloop()

Related

Can I change the menubar text after press a button? (Python, tkinter)

I started with python a month ago and I'm practicing different stuff. Right now I'm building a calculator and I'm adding a day/night mode switch on menubar. That was easy. But I'd like my menubar to show only "day mode" option when it's on night mode, and viceversa.
Tried a couple of things (like use a variable for the "add_command" and then try to do "variable.config()") but didn't work. Can such thing be done?
I hope I've explained myself good enough. Sorry if my english is not quite good. Here is a piece of the code:
def mododia():
seguro=messagebox.askquestion("Blah blah", "Blah blah blah")
if seguro=="yes":
File.config(background="white", fg="blue")
Edit.config(background="white", fg="blue")
Help.config(background="white", fg="blue")
[...]
def modonoche():
messagebox.showinfo("Blah blah", "Blah blah blah")
File.config(background="black", fg="orange")
Edit.config(background="black", fg="orange")
Help.config(background="black", fg="orange")
[...]
Edit=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Edit", menu=Edit)
Edit.add_command(label="Modo día", command=mododia)
Edit.add_command(label="Modo noche", command=modonoche)
Edit to add a reproducible example:
from tkinter import *
from tkinter import messagebox
root=Tk()
root.resizable(width=0, height=0)
def mododia():
seguro=messagebox.askquestion("Activar modo día", "Se recomienda no utilizar este modo con poca luz. ¿Está seguro de querer activar el modo día?")
if seguro=="yes":
File.config(background="white", fg="blue")
Edit.config(background="white", fg="blue")
Help.config(background="white", fg="blue")
frame1.config(bg="white")
frame2.config(bg="white")
previous.config(bg="white")
previouseq.config(bg="white")
display.config(bg="white", fg="black")
current.config(bg="white")
butclear.config(bg="white", fg="blue")
butdelete.config(bg="white", fg="blue")
butpercen.config(bg="white", fg="blue")
butdivide.config(bg="white", fg="blue")
but7.config(bg="white", fg="black")
but8.config(bg="white", fg="black")
but9.config(bg="white", fg="black")
butmulti.config(bg="white", fg="blue")
but4.config(bg="white", fg="black")
but5.config(bg="white", fg="black")
but6.config(bg="white", fg="black")
butsubs.config(bg="white", fg="blue")
but1.config(bg="white", fg="black")
but2.config(bg="white", fg="black")
but3.config(bg="white", fg="black")
butadd.config(bg="white", fg="blue")
butpotency.config(bg="white", fg="blue")
but0.config(bg="white", fg="black")
butdot.config(bg="white", fg="black")
butequal.config(bg="blue", fg="white")
root.config(bg="white")
def modonoche():
messagebox.showinfo("Activar modo noche", "Esta es la configuración recomendada por el creador del programa.")
File.config(background="black", fg="orange")
Edit.config(background="black", fg="orange")
Help.config(background="black", fg="orange")
frame1.config(bg="black")
frame2.config(bg="black")
previous.config(bg="black")
previouseq.config(bg="black")
display.config(bg="black", fg="white")
current.config(bg="black")
butclear.config(bg="black", fg="orange")
butdelete.config(bg="black", fg="orange")
butpercen.config(bg="black", fg="orange")
butdivide.config(bg="black", fg="orange")
but7.config(bg="black", fg="white")
but8.config(bg="black", fg="white")
but9.config(bg="black", fg="white")
butmulti.config(bg="black", fg="orange")
but4.config(bg="black", fg="white")
but5.config(bg="black", fg="white")
but6.config(bg="black", fg="white")
butsubs.config(bg="black", fg="orange")
but1.config(bg="black", fg="white")
but2.config(bg="black", fg="white")
but3.config(bg="black", fg="white")
butadd.config(bg="black", fg="orange")
butpotency.config(bg="black", fg="orange")
but0.config(bg="black", fg="white")
butdot.config(bg="black", fg="white")
butequal.config(bg="orange", fg="white")
root.config(bg="black")
def helpme():
ayuda=messagebox.showinfo("Ayuda", "Pulse las cifras con las que desea operar y las operaciones a realizar como en una calculadora corriente.")
def about():
acercade=messagebox.showinfo("Calculadora 1.0", "Primera versión de calculadora creada por Shinington.")
def exit():
salir=messagebox.askquestion("Cerrar calculadora", "¿Seguro que desea salir?")
if salir=="yes":
root.destroy()
def erase():
inputdis.set(0)
inputcurr.set(0)
def new():
erase()
inputprev.set(0)
inputpreq.set(0)
tools=Menu(root)
File=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="File", menu=File)
File.add_command(label="Nuevo", command=new)
File.add_command(label="Borrar", command=erase)
File.add_separator()
File.add_command(label="Salir", command=exit)
Edit=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Edit", menu=Edit)
Edit.add_command(label="Modo día", command=mododia)
Edit.add_command(label="Modo noche", command=modonoche)
Help=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Help", menu=Help)
Help.add_command(label="Ayuda", command=helpme)
Help.add_command(label="Acerca de...", command=about)
root.config(bg="black", menu=tools)
frame1=Frame(root)
frame1.pack()
frame2=Frame(root)
frame2.pack()
frame1.config(bg="black", width=40, height=30)
frame2.config(bg="black", width=40, height=60)
inputdis=IntVar()
inputprev=IntVar()
inputpreq=IntVar()
inputcurr=IntVar()
previous=Entry(frame1, textvariable=inputprev)
previous.grid(row=0, column=0, sticky="e")
previous.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
previouseq=Entry(frame1, textvariable=inputpreq)
previouseq.grid(row=1, column=0, sticky="e")
previouseq.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
display=Entry(frame1, textvariable=inputdis)
display.grid(row=2, column=0, pady=10, sticky="e")
display.config(fg="white", bg="black", font=("", 12, "bold"), width=30, justify="right", borderwidth=0)
current=Entry(frame1, textvariable=inputcurr)
current.grid(row=3, column=0, pady=10, sticky="e")
current.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
butclear=Button(frame2, text="AC", width=7)
butclear.grid(row=0, column=0, padx=5, pady=10)
butclear.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butdelete=Button(frame2, text="DEL", width=7)
butdelete.grid(row=0, column=1, padx=5, pady=10)
butdelete.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butpercen=Button(frame2, text="%", width=7)
butpercen.grid(row=0, column=2, padx=5, pady=10)
butpercen.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butdivide=Button(frame2, text=r"/", width=7)
butdivide.grid(row=0, column=3, padx=5, pady=10)
butdivide.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but7=Button(frame2, text="7", width=7)
but7.grid(row=1, column=0, padx=5, pady=10)
but7.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but8=Button(frame2, text="8", width=7)
but8.grid(row=1, column=1, padx=5, pady=10)
but8.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but9=Button(frame2, text="9", width=7)
but9.grid(row=1, column=2, padx=5, pady=10)
but9.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butmulti=Button(frame2, text="x", width=7)
butmulti.grid(row=1, column=3, padx=5, pady=10)
butmulti.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but4=Button(frame2, text="4", width=7)
but4.grid(row=2, column=0, padx=5, pady=10)
but4.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but5=Button(frame2, text="5", width=7)
but5.grid(row=2, column=1, padx=5, pady=10)
but5.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but6=Button(frame2, text="6", width=7)
but6.grid(row=2, column=2, padx=5, pady=10)
but6.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butsubs=Button(frame2, text="-", width=7)
butsubs.grid(row=2, column=3, padx=5, pady=10)
butsubs.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but1=Button(frame2, text="1", width=7)
but1.grid(row=3, column=0, padx=5, pady=10)
but1.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but2=Button(frame2, text="2", width=7)
but2.grid(row=3, column=1, padx=5, pady=10)
but2.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but3=Button(frame2, text="3", width=7)
but3.grid(row=3, column=2, padx=5, pady=10)
but3.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butadd=Button(frame2, text="+", width=7)
butadd.grid(row=3, column=3, padx=5, pady=10)
butadd.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butpotency=Button(frame2, text="x^", width=7)
butpotency.grid(row=4, column=0, padx=5, pady=10)
butpotency.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but0=Button(frame2, text="0", width=7)
but0.grid(row=4, column=1, padx=5, pady=10)
but0.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butdot=Button(frame2, text=".", width=7)
butdot.grid(row=4, column=2, padx=5, pady=10)
butdot.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butequal=Button(frame2, text="=", width=7)
butequal.grid(row=4, column=3, padx=5, pady=10)
butequal.config(fg="white", bg="orange", font=("", 10, "bold"), borderwidth=0)
root.mainloop()
There you can switch between "modo día" (day mode) and "modo noche" (night mode), but I'd like that only one of the options is available on the menu bar (night mode when day mode is selected and viceversa).
I don't want it to change automatically as time goes on, but to manually change it with the menubar. Can that be done with the entryconfigure that Bryan Oakley talks about? I don't know about the Flags Cool Cloud mention either. As I said, I've started programming a few weeks ago.
Delete this line:
Edit.add_command(label="Modo noche", command=modonoche)
Add these two line to your code:
def modonoche():
...
Edit.entryconfigure(0,label='mododia',command=mododia)
def mododia():
seguro=messagebox.askquestion("Activar modo día", "Se recomienda no utilizar este modo con poca luz. ¿Está seguro de querer activar el modo día?")
if seguro=="yes":
...
Edit.entryconfigure(0,label='modonoche',command=modonoche)
Source:
http://tcl.tk/man/tcl8.5/TkCmd/menu.htm#M55
This is your code with the modifications you want
from tkinter import *
from tkinter import messagebox
root=Tk()
root.resizable(width=0, height=0)
def mododia(): #Lite Mode
seguro=messagebox.askquestion("Activar modo día", "Se recomienda no utilizar este modo con poca luz. ¿Está seguro de querer activar el modo día?")
Edit.entryconfig(1,label = "Modo noche" , command = modonoche)
if seguro=="yes":
File.config(background="white", fg="blue")
Edit.config(background="white", fg="blue")
Help.config(background="white", fg="blue")
frame1.config(bg="white")
frame2.config(bg="white")
previous.config(bg="white")
previouseq.config(bg="white")
display.config(bg="white", fg="black")
current.config(bg="white")
butclear.config(bg="white", fg="blue")
butdelete.config(bg="white", fg="blue")
butpercen.config(bg="white", fg="blue")
butdivide.config(bg="white", fg="blue")
but7.config(bg="white", fg="black")
but8.config(bg="white", fg="black")
but9.config(bg="white", fg="black")
butmulti.config(bg="white", fg="blue")
but4.config(bg="white", fg="black")
but5.config(bg="white", fg="black")
but6.config(bg="white", fg="black")
butsubs.config(bg="white", fg="blue")
but1.config(bg="white", fg="black")
but2.config(bg="white", fg="black")
but3.config(bg="white", fg="black")
butadd.config(bg="white", fg="blue")
butpotency.config(bg="white", fg="blue")
but0.config(bg="white", fg="black")
butdot.config(bg="white", fg="black")
butequal.config(bg="blue", fg="white")
root.config(bg="white")
def modonoche(): #Dark Mode
messagebox.showinfo("Activar modo noche", "Esta es la configuración recomendada por el creador del programa.")
Edit.entryconfig(1,label = "Modo dia" , command = mododia)
File.config(background="black", fg="orange")
Edit.config(background="black", fg="orange")
Help.config(background="black", fg="orange")
frame1.config(bg="black")
frame2.config(bg="black")
previous.config(bg="black")
previouseq.config(bg="black")
display.config(bg="black", fg="white")
current.config(bg="black")
butclear.config(bg="black", fg="orange")
butdelete.config(bg="black", fg="orange")
butpercen.config(bg="black", fg="orange")
butdivide.config(bg="black", fg="orange")
but7.config(bg="black", fg="white")
but8.config(bg="black", fg="white")
but9.config(bg="black", fg="white")
butmulti.config(bg="black", fg="orange")
but4.config(bg="black", fg="white")
but5.config(bg="black", fg="white")
but6.config(bg="black", fg="white")
butsubs.config(bg="black", fg="orange")
but1.config(bg="black", fg="white")
but2.config(bg="black", fg="white")
but3.config(bg="black", fg="white")
butadd.config(bg="black", fg="orange")
butpotency.config(bg="black", fg="orange")
but0.config(bg="black", fg="white")
butdot.config(bg="black", fg="white")
butequal.config(bg="orange", fg="white")
root.config(bg="black")
def helpme():
ayuda=messagebox.showinfo("Ayuda", "Pulse las cifras con las que desea operar y las operaciones a realizar como en una calculadora corriente.")
def about():
acercade=messagebox.showinfo("Calculadora 1.0", "Primera versión de calculadora creada por Shinington.")
def exit():
salir=messagebox.askquestion("Cerrar calculadora", "¿Seguro que desea salir?")
if salir=="yes":
root.destroy()
def erase():
inputdis.set(0)
inputcurr.set(0)
def new():
erase()
inputprev.set(0)
inputpreq.set(0)
tools=Menu(root)
File=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="File", menu=File)
File.add_command(label="Nuevo", command=new)
File.add_command(label="Borrar", command=erase)
File.add_separator()
File.add_command(label="Salir", command=exit)
Edit=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Edit", menu=Edit)
Edit.add_command(label="Modo día", command=mododia)
Help=Menu(tools, tearoff=0, background="black", fg="orange")
tools.add_cascade(label="Help", menu=Help)
Help.add_command(label="Ayuda", command=helpme)
Help.add_command(label="Acerca de...", command=about)
root.config(bg="black", menu=tools)
frame1=Frame(root)
frame1.pack()
frame2=Frame(root)
frame2.pack()
frame1.config(bg="black", width=40, height=30)
frame2.config(bg="black", width=40, height=60)
inputdis=IntVar()
inputprev=IntVar()
inputpreq=IntVar()
inputcurr=IntVar()
previous=Entry(frame1, textvariable=inputprev)
previous.grid(row=0, column=0, sticky="e")
previous.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
previouseq=Entry(frame1, textvariable=inputpreq)
previouseq.grid(row=1, column=0, sticky="e")
previouseq.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
display=Entry(frame1, textvariable=inputdis)
display.grid(row=2, column=0, pady=10, sticky="e")
display.config(fg="white", bg="black", font=("", 12, "bold"), width=30, justify="right", borderwidth=0)
current=Entry(frame1, textvariable=inputcurr)
current.grid(row=3, column=0, pady=10, sticky="e")
current.config(fg="gray", bg="black", font=("", 8), width=40, justify="right", borderwidth=0)
butclear=Button(frame2, text="AC", width=7)
butclear.grid(row=0, column=0, padx=5, pady=10)
butclear.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butdelete=Button(frame2, text="DEL", width=7)
butdelete.grid(row=0, column=1, padx=5, pady=10)
butdelete.config(fg="orange", bg="black", font=("", 9, "bold"), borderwidth=0)
butpercen=Button(frame2, text="%", width=7)
butpercen.grid(row=0, column=2, padx=5, pady=10)
butpercen.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butdivide=Button(frame2, text=r"/", width=7)
butdivide.grid(row=0, column=3, padx=5, pady=10)
butdivide.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but7=Button(frame2, text="7", width=7)
but7.grid(row=1, column=0, padx=5, pady=10)
but7.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but8=Button(frame2, text="8", width=7)
but8.grid(row=1, column=1, padx=5, pady=10)
but8.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but9=Button(frame2, text="9", width=7)
but9.grid(row=1, column=2, padx=5, pady=10)
but9.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butmulti=Button(frame2, text="x", width=7)
butmulti.grid(row=1, column=3, padx=5, pady=10)
butmulti.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but4=Button(frame2, text="4", width=7)
but4.grid(row=2, column=0, padx=5, pady=10)
but4.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but5=Button(frame2, text="5", width=7)
but5.grid(row=2, column=1, padx=5, pady=10)
but5.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but6=Button(frame2, text="6", width=7)
but6.grid(row=2, column=2, padx=5, pady=10)
but6.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butsubs=Button(frame2, text="-", width=7)
butsubs.grid(row=2, column=3, padx=5, pady=10)
butsubs.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but1=Button(frame2, text="1", width=7)
but1.grid(row=3, column=0, padx=5, pady=10)
but1.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but2=Button(frame2, text="2", width=7)
but2.grid(row=3, column=1, padx=5, pady=10)
but2.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
but3=Button(frame2, text="3", width=7)
but3.grid(row=3, column=2, padx=5, pady=10)
but3.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butadd=Button(frame2, text="+", width=7)
butadd.grid(row=3, column=3, padx=5, pady=10)
butadd.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
butpotency=Button(frame2, text="x^", width=7)
butpotency.grid(row=4, column=0, padx=5, pady=10)
butpotency.config(fg="orange", bg="black", font=("", 10, "bold"), borderwidth=0)
but0=Button(frame2, text="0", width=7)
but0.grid(row=4, column=1, padx=5, pady=10)
but0.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butdot=Button(frame2, text=".", width=7)
butdot.grid(row=4, column=2, padx=5, pady=10)
butdot.config(fg="white", bg="black", font=("", 10, "bold"), borderwidth=0)
butequal=Button(frame2, text="=", width=7)
butequal.grid(row=4, column=3, padx=5, pady=10)
butequal.config(fg="white", bg="orange", font=("", 10, "bold"), borderwidth=0)
root.mainloop()

Why is the image not showing in the tkinter using if conditions? [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 1 year ago.
from tkinter import *
from tkinter import ttk
from PIL import ImageTk ,Image
win=tkinter.Toplevel()
wrapper=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper.place(x=0, y=80, width=465, height=625)
wrapper3=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper3.place(x=950, y=80, width=465, height=625)
wrapper3_title=Label(wrapper3, text="Selected Data", bg="crimson", fg="white", font=("times new roman",30,"bold"))
wrapper3_title.grid(row=0,column=0,padx=20, pady=10)
wrapper2=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper2.place(x=465, y=80, width=485, height=625)
ent8=StringVar()
def code():
btn1.destroy()
add=StringVar()
sub=StringVar()
pro=StringVar()
img=ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Label2= Label(wrapper2, image=img)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(wrapper, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(wrapper, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(wrapper, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(wrapper, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(wrapper, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(wrapper, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(wrapper, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(wrapper, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(wrapper, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
def img():
if ent8.get()=="4":
img=ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Label2= Label(wrapper3, image=img)
Label2.grid(row=0, column=2, padx=10, pady=5, sticky='w')
print("Move ahead")
else:
print("Try again")
btn2 = Button(wrapper, text = 'Image', command=img, bd = '5', width=15, height=2)
btn2.grid(row=12, column=1, padx=20, pady=10)
btn1 = Button(wrapper, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
Two images need to be shown on the tkinter. The one defined earlier in wrapper2, shows empty frame while the one that has to appear in wrapper3 after getting 4 as sum, does not appear at all. Moreover, the output printed is "Try again". Why it is so? When sum is 4 it has to show "Move ahead".
First of all, terrible names.
Both your function and your PhotoImage are named img. Rename the function to def add_img().
Second, looking at your code I have no idea what all the wrapper frames are for, why not name them according to what they are planned to hold? Same applies to all the widgets. Wouldn't calc_btn be a better name than btn? img_btn instead of btn2? Why do you need to read more than the name to know what something is?
Third, you have ent8 twice in your code. Once as Label and again as a StringVar.
Tkinter constantly refreshes your window so you need to save the image you are using.
Personally I would have done all of this in a class.
For right now, with your current code, just add
loaded_img = ImageTk.PhotoImage(Image.open("Amritsar.jpg")) before your functions and instead of using the variables you are using to open the image, just use Label(wrapper3, image=loaded_img)
As in:
win = Toplevel()
wrapper=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper.place(x=0, y=80, width=465, height=625)
wrapper3=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper3.place(x=950, y=80, width=465, height=625)
wrapper3_title=Label(wrapper3, text="Selected Data", bg="crimson", fg="white", font=("times new roman",30,"bold"))
wrapper3_title.grid(row=0,column=0,padx=20, pady=10)
wrapper2=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper2.place(x=465, y=80, width=485, height=625)
ent8=StringVar()
loaded_img = ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Edit
Here is the entire code:
from tkinter import *
from tkinter import ttk
from PIL import ImageTk ,Image
win=Toplevel()
wrapper=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper.place(x=0, y=80, width=465, height=625)
wrapper3=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper3.place(x=950, y=80, width=465, height=625)
wrapper3_title=Label(wrapper3, text="Selected Data", bg="crimson", fg="white", font=("times new roman",30,"bold"))
wrapper3_title.grid(row=0,column=0,padx=20, pady=10)
wrapper2=Frame(win, bd=4, relief=RIDGE, bg="crimson")
wrapper2.place(x=465, y=80, width=485, height=625)
ent8=StringVar()
loaded_img = ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
add_strvar = StringVar()
sub_strvar = StringVar()
pro_strvar = StringVar()
def code():
btn1.destroy()
Label2= Label(wrapper2, image=loaded_img)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
def Find():
add_strvar.set(float(ent00.get())+float(ent01.get()))
sub_strvar.set(float(ent00.get())-float(ent01.get()))
pro_strvar.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(wrapper, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(wrapper, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(wrapper, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(wrapper, textvariable=add_strvar, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(wrapper, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(wrapper, textvariable=sub_strvar, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(wrapper, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(wrapper, textvariable=pro_strvar, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(wrapper, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
def add_img():
if add_strvar.get() == "4.0":
Label2= Label(wrapper3, image=loaded_img)
Label2.grid(row=0, column=2, padx=10, pady=5, sticky='w')
print("Move ahead")
else:
print("Try again")
btn2 = Button(wrapper, text = 'Image', command=add_img, bd = '5', width=15, height=2)
btn2.grid(row=12, column=1, padx=20, pady=10)
btn1 = Button(wrapper, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
Edit 2
Code changed to work with classes:
from tkinter import *
from tkinter import ttk
from PIL import ImageTk ,Image
class ImageCalculator:
def __init__(self, img_path):
self.window = Toplevel()
self.window.geometry("1400x700+250+250")
self.mainframe = Frame(self.window)
self.mainframe.pack(expand=True, fill=BOTH)
self.bg_color = 'crimson'
frame_settings = {'master': self.mainframe, 'bd': 4,
'relief': RIDGE, 'bg': self.bg_color}
frame_names = ('left', 'center', 'right')
self.frames = {name: Frame(**frame_settings) for name in frame_names}
frame_height = 625
init_y = 80
frame_widths = {'left': 465, 'center': 485, 'right': 465}
x = 0
for name in frame_names:
frame_width = frame_widths[name]
self.frames[name].place(x=x, y=init_y, width=frame_width,
height=frame_height)
x += frame_width
self.setup_right_wrapper()
self.code_btn = self.setup_left_wrapper()
self.loaded_image = ImageTk.PhotoImage(Image.open(img_path))
self.add_strvar = StringVar()
self.sub_strvar = StringVar()
self.pro_strvar = StringVar()
def setup_left_wrapper(self) -> Button:
code_btn = Button(self.frames['left'], text='OPEN CODE', command=self.code,
bd='5', width=20, height=2)
img_btn = Button(self.frames['left'], text='Image', bd='5', width=15,
height=2, command=self.add_img)
code_btn.grid(row=11, column=1, padx=20, pady=10)
img_btn.grid(row=12, column=1, padx=20, pady=10)
return code_btn
def setup_right_wrapper(self):
right_frame_title = Label(self.frames['right'], text="Selected Data",
bg=self.bg_color, fg="white",
font=("times new roman",30,"bold"))
right_frame_title.grid(row=0, column=0, padx=20, pady=10)
def code(self):
def Find():
self.add_strvar.set(float(first_entry.get())
+ float(second_entry.get()))
self.sub_strvar.set(float(first_entry.get())
- float(second_entry.get()))
self.pro_strvar.set(float(first_entry.get())
* float(second_entry.get()))
self.code_btn.destroy()
Label2 = Label(self.frames['center'], image=self.loaded_image)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
left_frame = self.frames['left']
first_entry = Entry(left_frame, width=15)
second_entry = Entry(left_frame, width=15)
# Settings of all labels
lbl_settings = {'bg': self.bg_color, 'fg': 'white',
'font': ("times new roman", 15, "bold")}
# Setting of all entry.
entry_settings = {'width': 15, 'state': 'readonly'}
add_lbl = Label(left_frame, text="Add", **lbl_settings)
add_entry = Entry(left_frame, textvariable=self.add_strvar,
**entry_settings)
sub_lbl = Label(left_frame, text="Subtract", **lbl_settings)
sub_entry = Entry(left_frame, textvariable=self.sub_strvar,
**entry_settings)
pro_lbl = Label(left_frame, text="Product", **lbl_settings)
pro_entry = Entry(left_frame, textvariable=self.pro_strvar,
**entry_settings)
calc_btn = Button(left_frame, text='Calculate', command=Find, bd='5',
width=15, height=2)
# Widget placement.
first_entry.grid(row=4, column=1, padx=10, pady=10, sticky='w')
second_entry.grid(row=5, column=1, padx=10, pady=10, sticky='w')
add_lbl.grid(row=6, column=0, padx=20, pady=10, sticky='w')
add_entry.grid(row=6, column=1, padx=10, pady=10, sticky='w')
sub_lbl.grid(row=7, column=0, padx=20, pady=10, sticky='w')
sub_entry.grid(row=7, column=1, padx=10, pady=10, sticky='w')
pro_lbl.grid(row=8, column=0, padx=20, pady=10, sticky='w')
pro_entry.grid(row=8, column=1, padx=10, pady=10, sticky='w')
calc_btn.grid(row=11, column=1, padx=20, pady=10)
def add_img(self):
if self.add_strvar.get() == "4.0":
Label2 = Label(self.frames['right'], image=self.loaded_image)
Label2.grid(row=0, column=2, padx=10, pady=5, sticky='w')
print("Move ahead")
else:
print("Try again")
def main():
img_calc = ImageCalculator('Amritsar.jpg')
mainloop()
if __name__ == "__main__":
main()
After setting an image for a Label, you need to keep a reference to this image. Otherwise, it's removed at the end of the function and you lose the image (it's garbage collected).
So, when you define your label, just add a line that stores the image as an attribute of the label:
img=ImageTk.PhotoImage(Image.open("Amritsar.jpg"))
Label2= Label(wrapper2, image=img)
Label2.grid(row=0, column=0, padx=10, pady=5, sticky='w')
Label2.dontloseit = img
The Label2 widget now has a nonsensical attribute called .dontloseit which holds the image. Now, it won't get collected and it will show in your tkinter widget.
It's one of the peculiarities of tkinter.

Why the 1st code runs and 2nd doesn't after defining it?

The 1st code completely works fine.
1st Code
from tkinter import *
from tkinter import ttk
win=Tk()
add=StringVar()
sub=StringVar()
pro=StringVar()
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(win, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(win, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(win, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(win, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(win, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(win, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(win, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(win, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(win, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
But when I define it i.e. make it a function (As in the code below), it doesn't work. Also it doesn't even show any error. I am not understanding the reason for this issue.
2nd Code:
from tkinter import *
from tkinter import ttk
win=Tk()
def code():
win=Tk()
add=StringVar()
sub=StringVar()
pro=StringVar()
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(win, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(win, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(win, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(win, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(win, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(win, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(win, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(win, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(win, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
btn1 = Button(win, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
Is there any kind of mistake I am doing leading to its non-working? ______________________
You are redefining win and then performing actions on that, which doesn't seem to play nice together. If you want to clear the screen and place new widgets, here's how I would do it:
from tkinter import *
from tkinter import ttk
win=Tk()
def code():
btn1.destroy()
add=StringVar()
sub=StringVar()
pro=StringVar()
def Find():
add.set(float(ent00.get())+float(ent01.get()))
sub.set(float(ent00.get())-float(ent01.get()))
pro.set(float(ent00.get())*float(ent01.get()))
ent00=Entry(win, width=15)
ent00.grid(row=4, column=1, padx=10, pady=10, sticky='w')
ent01=Entry(win, width=15)
ent01.grid(row=5, column=1, padx=10, pady=10, sticky='w')
lbl8=Label(win, text="Add", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=6, column=0, padx=20, pady=10, sticky='w')
ent8=Entry(win, textvariable=add, width=15, state='readonly')
ent8.grid(row=6, column=1, padx=10, pady=10, sticky='w')
lbl15=Label(win, text="Subtract", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=7, column=0, padx=20, pady=10, sticky='w')
ent15=Entry(win, textvariable=sub, width=15, state='readonly')
ent15.grid(row=7, column=1, padx=10, pady=10, sticky='w')
lbl9=Label(win, text="Product", bg="crimson", fg="white", font=("times new roman",15,"bold")).grid(row=8, column=0, padx=20, pady=10, sticky='w')
ent9=Entry(win, textvariable=pro, width=15, state='readonly')
ent9.grid(row=8, column=1, padx=10, pady=10, sticky='w')
btn = Button(win, text = 'Calculate', command=Find, bd = '5', width=15, height=2)
btn.grid(row=11, column=1, padx=20, pady=10)
btn1 = Button(win, text = 'OPEN CODE', command=code, bd = '5', width=20, height=2)
btn1.grid(row=11, column=1, padx=20, pady=10)
win.geometry("1400x700+250+250")
win.mainloop()
I just removed the three lines modifying win in the code function and added btn1.destroy(), which removes the button we want to stop displaying from the window.

Hi, I am trying to build a simple calculator (just adds) in Spyder using python. How do I define end so that it will delete the previous number?

import tkinter as tk
root = tk.Tk()
root.title("Simple Calculator")
e= tk.Entry(root,width=35, borderwidth=5)
e.grid(row=0,column=0, columnspan=3, padx=10, pady=10)
#define button_click
def button_click(number):
e.delete(0,END)
e.insert(0,number)
#Define Buttons
button_1 = tk.Button(root, text="1", padx=40, pady=20, command= lambda: button_click(1))
button_2 = tk.Button(root, text="2", padx=40, pady=20, command= lambda: button_click(2))
button_3 = tk.Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = tk.Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = tk.Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = tk.Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = tk.Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = tk.Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = tk.Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9))
button_0 = tk.Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0))
button_add = tk.Button(root, text="+", padx=39, pady=20, command=lambda: button_click())
button_equal = tk.Button(root, text="=", padx=91, pady=20, command=lambda: button_click())
button_clear = tk.Button(root, text="Clear", padx=79, pady=20, command=lambda: button_click())
# Put the buttons on the screen
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_clear.grid(row=4, column=1, columnspan=2)
button_add.grid(row=5, column=0)
button_equal.grid(row=5, column=1, columnspan=2)
root.mainloop()
Simply
def button_click(number):
e.delete(0, tk.END) # tk.END instead of END
e.insert(0,number)
This is because you've used
import tkinter as tk
which means that all functions that are inside tkinter are stored in the tk variable.

Need help collecting data from buttons pressed. [Python]

I'm trying to create a roulette table (which I have done as a GUI). Now, when I press the button for the outcome it shows the number in my top box, but I'm struggling to find a way to collect the results in a list, so I can then later pull data from the list.
For example, I want a list of past results so that I could show that's it's been 4 spins without landing on a odd number or it's been 3 spins since it's been red, or on average it lands in the 1st 12 every 3 spins.
I have tried numerous ways of collecting results from the buttons clicked but nothing works.
from tkinter import*
# Roulette GUI
root = Tk()
root.title("Roulette")
e = Entry(root, width=200, borderwidth=5)
e.grid(row=0, column=0, columnspan=13, padx=10, pady=10)
def button_click(number):
e.delete(0, END)
e.insert(0, number)
print(number)
# define buttons
button_0 = Button(root, text="0", padx=40, pady=84, bg='green', command=lambda: button_click(0))
button_1 = Button(root, text="1", padx=40, pady=20, bg='red', command=lambda: button_click(1))
button_2 = Button(root, text="2", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(2))
button_3 = Button(root, text="3", padx=40, pady=20, bg='red', command=lambda: button_click(3))
button_4 = Button(root, text="4", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(4))
button_5 = Button(root, text="5", padx=40, pady=20, bg='red', command=lambda: button_click(5))
button_6 = Button(root, text="6", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(6))
button_7 = Button(root, text="7", padx=40, pady=20, bg='red', command=lambda: button_click(7))
button_8 = Button(root, text="8", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(8))
button_9 = Button(root, text="9", padx=40, pady=20, bg='red', command=lambda: button_click(9))
button_10 = Button(root, text="10", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(10))
button_11 = Button(root, text="11", padx=40, pady=20, bg='red', command=lambda: button_click(11))
button_12 = Button(root, text="12", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(12))
button_13 = Button(root, text="13", padx=40, pady=20, bg='red', command=lambda: button_click(13))
button_14 = Button(root, text="14", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(14))
button_15 = Button(root, text="15", padx=40, pady=20, bg='red', command=lambda: button_click(15))
button_16 = Button(root, text="16", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(16))
button_17 = Button(root, text="17", padx=40, pady=20, bg='red', command=lambda: button_click(17))
button_18 = Button(root, text="18", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(18))
button_19 = Button(root, text="19", padx=40, pady=20, bg='red', command=lambda: button_click(19))
button_20 = Button(root, text="20", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(20))
button_21 = Button(root, text="21", padx=40, pady=20, bg='red', command=lambda: button_click(21))
button_22 = Button(root, text="22", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(22))
button_23 = Button(root, text="23", padx=40, pady=20, bg='red', command=lambda: button_click(23))
button_24 = Button(root, text="24", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(24))
button_25 = Button(root, text="25", padx=40, pady=20, bg='red', command=lambda: button_click(25))
button_26 = Button(root, text="26", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(26))
button_27 = Button(root, text="27", padx=40, pady=20, bg='red', command=lambda: button_click(27))
button_28 = Button(root, text="28", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(28))
button_29 = Button(root, text="29", padx=40, pady=20, bg='red', command=lambda: button_click(29))
button_30 = Button(root, text="30", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(30))
button_31 = Button(root, text="31", padx=40, pady=20, bg='red', command=lambda: button_click(31))
button_32 = Button(root, text="32", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(32))
button_33 = Button(root, text="33", padx=40, pady=20, bg='red', command=lambda: button_click(33))
button_34 = Button(root, text="34", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(34))
button_35 = Button(root, text="35", padx=40, pady=20, bg='red', command=lambda: button_click(35))
button_36 = Button(root, text="36", padx=40, pady=20, bg='black', fg='white', command=lambda: button_click(36))
button_exit = Button(root, text="Exit", padx=60, pady=20, command=root.quit)
# put buttons on the screen
button_0.grid(row=1, rowspan=3, column=0)
button_1.grid(row=3, column=1)
button_2.grid(row=2, column=1)
button_3.grid(row=1, column=1)
button_4.grid(row=3, column=2)
button_5.grid(row=2, column=2)
button_6.grid(row=1, column=2)
button_7.grid(row=3, column=3)
button_8.grid(row=2, column=3)
button_9.grid(row=1, column=3)
button_10.grid(row=3, column=4)
button_11.grid(row=2, column=4)
button_12.grid(row=1, column=4)
button_13.grid(row=3, column=5)
button_14.grid(row=2, column=5)
button_15.grid(row=1, column=5)
button_16.grid(row=3, column=6)
button_17.grid(row=2, column=6)
button_18.grid(row=1, column=6)
button_19.grid(row=3, column=7)
button_20.grid(row=2, column=7)
button_21.grid(row=1, column=7)
button_22.grid(row=3, column=8)
button_23.grid(row=2, column=8)
button_24.grid(row=1, column=8)
button_25.grid(row=3, column=9)
button_26.grid(row=2, column=9)
button_27.grid(row=1, column=9)
button_28.grid(row=3, column=10)
button_29.grid(row=2, column=10)
button_30.grid(row=1, column=10)
button_31.grid(row=3, column=11)
button_32.grid(row=2, column=11)
button_33.grid(row=1, column=11)
button_34.grid(row=3, column=12)
button_35.grid(row=2, column=12)
button_36.grid(row=1, column=12)
button_exit.grid(row=4, column=11, columnspan=2)
root.mainloop()
if you are trying to see percentage of pressing red and black buttons, this code print it on your console
from tkinter import*
root = Tk()
root.title("Roulette")
e = Entry(root, width=200, borderwidth=5)
e.grid(row=0, column=0, columnspan=13, padx=10, pady=10)
results = []
def button_click(number):
e.delete(0, END)
e.insert(0, number)
results.append(number)
#loop through results
count = 0
for i in range(len(results)):
if results[i]%2 == 0:
count += 1
print("Number is",number)
red_percentage = count/len(results)*100
print("Black", 100-red_percentage)
print("Red", red_percentage)
print("------------------------------------")
# define buttons
button = Button(root, text="0", padx=40, pady=84, bg='green', command=lambda: button_click(0))
button.grid(row=1, rowspan=3, column=0)
for i in range(0,36):
if i%2 == 0:
button = Button(root, text=str(i+1), padx=40, pady=20, bg='black', fg='white', command=lambda i=i:button_click(i+1))
else:
button = Button(root, text=str(i+1), padx=40, pady=20, bg='red', command=lambda i=i: button_click(i+1))
button.grid(row=3 - i%3, column=int(i/3) + 1)
button = Button(root, text="Exit", padx=60, pady=20, command=root.quit)
button.grid(row=4, column=11, columnspan=2)
root.mainloop()

Categories

Resources