So I am trying to each time you click one of the buttons that doesn't have the bomb, for the variable "score" to update and immediately being displayed on the bottom. But when I click one of them, the displayed variable is not updated for some reason even though I explicitly said for the "Label" being displayed to have the "text=score". I know my code is quite long and not really efficient but I am a bit new to python and I'm still learning. What could I fix in my code to solve this issue? ANY help is appreciated!
from tkinter import *
import random
screen = Tk()
ticket = random.randint(1,3)
score = 0
def test():
ticket1 = random.randint(1,3)
ticket2 = random.randint(1,3)
def test1():
if ticket1 == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=1, column=0, sticky="w")
else:
button_2 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_2.grid(row=1, column=0, sticky="w")
global score
score += 1
def test2():
if ticket1 == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=1, column=1, sticky="w")
else:
button_4 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_4.grid(row=1, column=1, sticky="w")
global score
score += 1
def test3():
if ticket1 == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=1, column=2, sticky="w")
else:
button_6 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_6.grid(row=1, column=2, sticky="w")
global score
score += 1
def test4():
if ticket2 == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=0, column=0, sticky="w")
else:
button_2 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_2.grid(row=0, column=0, sticky="w")
global score
score += 2
def test5():
if ticket2 == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=0, column=1, sticky="w")
else:
button_4 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_4.grid(row=0, column=1, sticky="w")
global score
score += 2
def test6():
if ticket2 == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=0, column=2, sticky="w")
else:
button_6 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_6.grid(row=0, column=2, sticky="w")
global score
score += 2
button1 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=1, column=0, sticky="w")
button1 = 1
button2 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=1, column=1, sticky="w"+"e"+"n"+"s")
button2 = 2
button3 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=1, column=2, sticky="e")
button3 = 3
button4 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test4)
button4.grid(row=0, column=0, sticky="w")
button4 = 1
button5 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test5)
button5.grid(row=0, column=1, sticky="w"+"e"+"n"+"s")
button5 = 2
button6 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test6)
button6.grid(row=0, column=2, sticky="e")
button6 = 3
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=8, columnspan=3, sticky="w"+"e"+"n"+"s")
scoreText = Label(screen, text="Score: " + str(score), width=25, height=2)
scoreText.grid(row=9, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
After you change score you have to replace text in label
score += 1
scoreText['text'] = "Score: " + str(score)
Full code which replaces text in buttons instead of creating new ones.
import tkinter as tk
import random
def test():
def test1():
global score
if ticket1 == 1:
button1.config(text="RIP", bg="red")
else:
button1.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test2():
global score
if ticket1 == 2:
button2.config(text="RIP", bg="red")
else:
button2.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test3():
global score
if ticket1 == 3:
button3.config(text="RIP", bg="red")
else:
button3.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test4():
global score
if ticket2 == 1:
button4.config(text="RIP", bg="red")
else:
button4.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test5():
global score
if ticket2 == 2:
button5.config(text="RIP", bg="red")
else:
button5.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test6():
global score
if ticket2 == 3:
button6.config(text="RIP", bg="red")
else:
button6.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
ticket1 = random.randint(1, 3)
ticket2 = random.randint(1, 3)
button1 = tk.Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=1, column=0, sticky="w")
button2 = tk.Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=1, column=1, sticky="wens")
button3 = tk.Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=1, column=2, sticky="e")
button4 = tk.Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test4)
button4.grid(row=0, column=0, sticky="w")
button5 = tk.Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test5)
button5.grid(row=0, column=1, sticky="wens")
button6 = tk.Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test6)
button6.grid(row=0, column=2, sticky="e")
# --- main --
score = 0
screen = tk.Tk()
button_start = tk.Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button_start.grid(row=8, columnspan=3, sticky="wens")
label_score = tk.Label(screen, text="Score: 0", width=25, height=2)
label_score.grid(row=9, columnspan=3, sticky="wens")
screen.mainloop()
Related
If I run the following code alone, it displays the text in the grid while running:
def solve_wumpus_world(master, world_file):
world = World()
world.generate_world(world_file)
label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
agent = Agent(world, label_grid)
# Agent Solving
while agent.exited == False:
agent.explore()
if agent.found_gold == True:
agent.leave_cave()
break
agent.repaint_world()
agent.world_knowledge[agent.world.agent_row][agent.world.agent_col].remove('A')
time.sleep(1.5)
agent.repaint_world()
# GUI
def aigui():
game = Tk()
game.title("Hunt the Wumpus")
game.configure(bg="DarkOrchid4")
game.geometry("2000x2000")
game.iconbitmap(r'Images\Monster.ico')
world = World()
world.generate_world("world_1.txt")
grid = LabelFrame(game, text="GRID", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 24")
worldLabel = LabelFrame(game, text="MENU", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 20")
label_grid = [[Grid_Label(grid, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
world_1 = Button(worldLabel, text="WORLD ONE", command=lambda: solve_wumpus_world(grid, "world_1.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
world_2 = Button(worldLabel, text="WORLD TWO", command=lambda: solve_wumpus_world(grid, "world_2.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
world_3 = Button(worldLabel, text="WORLD THREE", command=lambda: solve_wumpus_world(grid, "world_3.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
world_4 = Button(worldLabel, text="WORLD FOUR", command=lambda: solve_wumpus_world(grid, "world_4.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
quitButton = Button(worldLabel, text="QUIT", padx=40, font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green",
borderwidth=0, activeforeground="chartreuse2", activebackground="Indigo", command=lambda:game.destroy())
grid.pack(padx=1,pady=1)
worldLabel.pack(padx=5, pady=5)
world_1.grid(row=0, column=0, padx=10, pady=10, sticky=EW)
world_2.grid(row=0, column=1, padx=10, pady=10, sticky=EW)
world_3.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
world_4.grid(row=0, column=3, padx=10, pady=10, sticky=EW)
quitButton.grid(row=1, column=1, columnspan=2, padx=10, pady=10, sticky=EW)
game.mainloop()
It shows the text inside the grid when gaming is being played
But when I call the above code from another class like a main class which has a main menu which further opens this game window, the game works fine and the boxes are also highlighted but the text isn't displayed. For example, the code below
def solve_wumpus_world(master, world_file):
world = World()
world.generate_world(world_file)
label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
agent = Agent(world, label_grid)
# Agent Solving
while agent.exited == False:
agent.explore()
if agent.found_gold == True:
agent.leave_cave()
break
agent.repaint_world()
agent.world_knowledge[agent.world.agent_row][agent.world.agent_col].remove('A')
time.sleep(1.5)
agent.repaint_world()
# GUI
def aigui():
game = Tk()
game.title("Hunt the Wumpus")
game.configure(bg="DarkOrchid4")
game.geometry("2000x2000")
game.iconbitmap(r'Images\Monster.ico')
world = World()
world.generate_world("world_1.txt")
grid = LabelFrame(game, text="GRID", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 24")
worldLabel = LabelFrame(game, text="MENU", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 20")
label_grid = [[Grid_Label(grid, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
world_1 = Button(worldLabel, text="WORLD ONE", command=lambda: solve_wumpus_world(grid, "world_1.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
world_2 = Button(worldLabel, text="WORLD TWO", command=lambda: solve_wumpus_world(grid, "world_2.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
world_3 = Button(worldLabel, text="WORLD THREE", command=lambda: solve_wumpus_world(grid, "world_3.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
world_4 = Button(worldLabel, text="WORLD FOUR", command=lambda: solve_wumpus_world(grid, "world_4.txt"), padx=40,
font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
activeforeground="chartreuse2", activebackground="Indigo")
quitButton = Button(worldLabel, text="QUIT", padx=40, font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green",
borderwidth=0, activeforeground="chartreuse2", activebackground="Indigo", command=lambda:game.destroy())
grid.pack(padx=1,pady=1)
worldLabel.pack(padx=5, pady=5)
world_1.grid(row=0, column=0, padx=10, pady=10, sticky=EW)
world_2.grid(row=0, column=1, padx=10, pady=10, sticky=EW)
world_3.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
world_4.grid(row=0, column=3, padx=10, pady=10, sticky=EW)
quitButton.grid(row=1, column=1, columnspan=2, padx=10, pady=10, sticky=EW)
game.mainloop()
def maingui():
root = Tk()
root.geometry("600x600")
root.title("Hunt the Wumpus - Game")
root.configure(bg="DarkOrchid4")
root.iconbitmap(r'Images\Monster.ico')
# Label
myLabel = LabelFrame(root, text="Hunt the Wumpus", fg="lawn green", bg="DarkOrchid4", padx=100, pady=100)
textFont = ("Creepster", 24)
myLabel.config(font=textFont)
# Functions
# Buttons
buttonFont = ("Leichenhaus", 16)
aiButton = Button(myLabel, text="GAME", fg="lawn green", bg="DarkViolet",
activeforeground="chartreuse2", activebackground="Indigo", padx=40, command=aigui)
aiButton.config(font=buttonFont)
creditButton = Button(myLabel, text="Credits", fg="lawn green", bg="DarkViolet",
activeforeground="chartreuse2", activebackground="Indigo", padx=40)
creditButton.config(font=buttonFont)
quitButton = Button(myLabel, text="Quit", fg="lawn green", bg="DarkViolet",
activeforeground="chartreuse2", activebackground="Indigo", padx=40, command=lambda: root.destroy())
quitButton.config(font=buttonFont)
# Packing on Screen
myLabel.pack(padx=10, pady=10)
aiButton.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
creditButton.grid(row=1, column=2, padx=10, pady=10, sticky=EW)
quitButton.grid(row=3, column=2, padx=10, pady=10, sticky=EW)
root.mainloop()
maingui()
This code calls the above code from a method when the button is pressed.
Text not being displayed but the game is working fine.
from tkinter import *
import pywhatkit
import time
root = Tk()
root.title("whatsapp")
root.geometry('405x1000')
root.resizable(width=0, height=0)
label = Label(root, text="Whatsapp Automation", font='bold', width=40 , fg='white',
bg='black', padx=10, pady=13)
label.grid(row=0, columnspan=3, padx=10, pady=10)
label.place(x=10, y=10)
#form1
label=Label(root, text="whatsapp numbers", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=90)
number_str = StringVar()
entry1 = (Text(root,width=30, textvariable=number_str, bd=6, font=14, borderwidth=6))
entry1.insert(0,"+")
entry1.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry1.place(x=10, y=120)
#form2
label=Label(root, text="الرسالة", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=360)
message_str = StringVar()
entry2 = (Text(root, width=41, textvariable=message_str, bd=6, font=14, borderwidth=6))
entry2.insert(0, "write your message")
entry2.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry2.place(x=10, y=400)
#time
label=Label(root, text="وقت الانتظار24/الساعة", font=20 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=450)
labe4=Label(root, font=20 , fg="white", bg="black")
labe4.grid(row=1, padx=10, pady=10)
labe4.place(x = 220, y=450)
#time function
def localtime():
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
labe4.config(text="localtime:"+current_time)
labe4.after(200, localtime)
localtime()
entry3 = (Entry(root, width=20))
entry3.insert(0, "15")
entry3.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry3.place(x=15, y=490)
entry4 = (Entry(root, width=20))
entry4.insert(0, "20")
entry4.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry4.place(x=150, y=490)
#whatsapp send
def whatsapp():
number = entry1.get()
message = entry2.get()
time1 = int(entry3.get())
time2 = int(entry4.get())
pywhatkit.sendwhatmsg(number, message,time1,time2)
send = Button(root, font="30", width=40, text="ارسال" , fg="black",
bg="gold" , bd=10,
command=whatsapp)
send.grid(row=3, column=1, padx=10, pady=10)
send.place(x = 15 , y = 520)
root.mainloop()
I want to solve this problem without replacing Entry with Text in
#form1
entry1 = (Text(root,width=30, textvariable=number_str, bd=6, font=14, borderwidth=6))
and
entry2 = (Text(root, width=41, textvariable=message_str, bd=6, font=14, borderwidth=6))
I can't solve this problem. Code is not running.
The issue's in:
entry2 = (Text(root, width=41, textvariable=message_str, bd=6, font=14, borderwidth=6))
entry1 = (Text(root,width=30, textvariable=number_str, bd=6, font=14, borderwidth=6))
Try this.
from tkinter import *
import pywhatkit
import time
root = Tk()
root.title("whatsapp")
root.geometry('405x1000')
root.resizable(width=0, height=0)
label = Label(root, text="Whatsapp Automation", font='bold', width=40 , fg='white',
bg='black', padx=10, pady=13)
label.grid(row=0, columnspan=3, padx=10, pady=10)
label.place(x=10, y=10)
#form1
label=Label(root, text="whatsapp numbers", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=90)
number_str = StringVar()
entry1 = Text(root,width=30, bd=6, font=14, borderwidth=6)
entry1.insert('end',"+")
entry1.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry1.place(x=10, y=120)
#form2
label=Label(root, text="الرسالة", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=360)
message_str = StringVar()
entry2 = (Text(root, width=41, bd=6, font=14, borderwidth=6))
entry2.insert('end', "write your message")
entry2.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry2.place(x=10, y=400)
#time
label=Label(root, text="وقت الانتظار24/الساعة", font=20 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=450)
labe4=Label(root, font=20 , fg="white", bg="black")
labe4.grid(row=1, padx=10, pady=10)
labe4.place(x = 220, y=450)
#time function
def localtime():
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
labe4.config(text="localtime:"+current_time)
labe4.after(200, localtime)
localtime()
entry3 = (Entry(root, width=20))
entry3.insert(0, "15")
entry3.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry3.place(x=15, y=490)
entry4 = (Entry(root, width=20))
entry4.insert(0, "20")
entry4.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry4.place(x=150, y=490)
#whatsapp send
def whatsapp():
number = number_str.get()
message = message_str.get()
time1 = int(entry3.get())
time2 = int(entry4.get())
pywhatkit.sendwhatmsg(number, message,time1,time2)
send = Button(root, font="30", width=40, text="ارسال" , fg="black",
bg="gold" , bd=10,
command=whatsapp)
send.grid(row=3, column=1, padx=10, pady=10)
send.place(x = 15 , y = 520)
root.mainloop()
Output:
]
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.
So my intention is when the user clicks one of the buttons, for the rest of the other buttons not to perform anything even when clicked, so basically to stop the buttons from performing their commands when the user clicks them ONLY if they have clicked in another button previously, I don't know if I expressed myself well so I am sorry if I dind't but here's my code:
from tkinter import *
import random
screen = Tk()
ticket = random.randint(1,3)
def test():
def test1():
if ticket == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=0, column=0, sticky="w")
else:
button_2 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_2.grid(row=0, column=0, sticky="w")
def test2():
if ticket == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=0, column=1, sticky="w")
else:
button_4 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_4.grid(row=0, column=1, sticky="w")
def test3():
if ticket == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=0, column=2, sticky="w")
else:
button_6 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_6.grid(row=0, column=2, sticky="w")
ticket = random.randint(1,3)
button1 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=0, column=0, sticky="w")
button1 = 1
button2 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=0, column=1, sticky="w"+"e"+"n"+"s")
button2 = 2
button3 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=0, column=2, sticky="e")
button3 = 3
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
You can set the state of the other Buttons to DISABLED to grey them out and prevent clicks. This would be the ideal place to use a subclass that keeps track of its instances.
from tkinter import *
import random
screen = Tk()
class MykoButton(Button):
instances = []
def __init__(self, master=None, **kwargs):
super().__init__(master, command=self.run, **kwargs)
self.instances.append(self)
def run(self):
for button in self.instances:
if button is not self:
button.config(state=DISABLED)
if random.randint(1,3) == 1:
self.config(text="RIP", fg="white", bg="red") # update the button
else:
self.config(text="+1", fg="white", bg="green")
def test():
for i in range(3):
button = MykoButton(screen, text="1", fg="white", bg="blue", width=15, height=2)
button.grid(row=0, column=i)
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
Also, note that I changed your code to update the clicked button, rather than put a new button on top of it.
My code for my messagebox won't work on my window. Everything else works but when I run it my "About" messagebox won't show up. I want my messagebox to pop out when "About" is clicked on my window. What can I do to make it work?
from tkinter import *
from tkinter import messagebox
calculator = Tk()
calculator.title("Calculator")
calculator.geometry("317x145")
menubar = Menu(calculator)
class Calculator(Frame):
def __init__(self):
Frame.__init__(self)
display = Frame(calculator, bd=0, width=1000, height=1000, relief=SUNKEN)
buttons = Frame(calculator, bd=0, width=7, height=1, relief=GROOVE)
display.grid(column=0, row=0, padx=0, pady=0)
buttons.grid(column=0, row=1, padx=1)
numbers = StringVar()
self.results = Entry(display, textvariable=numbers, width=31, fg="DarkOrchid4", bg="lavender blush", font="Verdana")
self.results.pack()
self.results.grid(column=0, row=0)
def showup(x):
return lambda: self.results.insert(END, x)
numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for i in range(9):
n=numbers[i]
Button(buttons, bg="snow", text=n, width=7, height=1, command=showup(n), relief=RAISED).grid(row=i%3, column=i//3)
Clear = Button(buttons, bg="snow", text="C", width=7, height=1, command=self.clear, relief=RAISED)
Clear.grid(padx=2, pady=2, column=3, row=0)
Equals = Button(buttons, bg="snow", text="=", width=7, height=1, command=self.equals, relief=RAISED)
Equals.grid(padx=2, pady=2, column=4, row=3)
All_clear = Button(buttons, bg="snow", text="AC", width=7, height=1, command=self.all_clear, relief=RAISED)
All_clear.grid(padx=2, pady=2, column=4, row=0)
Bracket_one = Button(buttons, bg="snow", text="(", width=7, height=1, command=self.bracket_one, relief=RAISED)
Bracket_one.grid(padx=2, pady=2, column=2, row=3)
Bracket_two = Button(buttons, bg="snow", text=")", width=7, height=1, command=self.bracket_two, relief=RAISED)
Bracket_two.grid(padx=2, pady=2, column=3, row=3)
Zero = Button(buttons, bg="snow", text="0", width=7, height=1, command=self.zero, relief=RAISED)
Zero.grid(padx=2, pady=2, column=0, row=3)
Decimal_point = Button(buttons, bg="snow", text=".", width=7, height=1, command=self.decimal_point, relief=RAISED)
Decimal_point.grid(padx=2, pady=2, column=1, row=3)
Multiplication = Button(buttons, bg="red", text="x", width=7, height=1, command=self.multiplication, relief=RAISED)
Multiplication.grid(padx=2, pady=2, column=3, row=1)
Division = Button(buttons, bg="powder blue", text="/", width=7, height=1, command=self.division, relief=RAISED)
Division.grid(padx=2, pady=2, column=4, row=1)
Addition = Button(buttons, bg="yellow", text="+", width=7, height=1, command=self.addition, relief=RAISED)
Addition.grid(padx=2, pady=2, column=3, row=2)
Subtraction = Button(buttons, bg="green", text="-", width=7, height=1, command=self.subtraction, relief=RAISED)
Subtraction.grid(padx=2, pady=2, column=4, row=2)
def equals(self):
try:
result = eval(self.results.get())
except:
result = "Invalid input"
self.all_clear()
self.results.insert(0, result)
def zero(self):
self.results.insert(END, "0")
def bracket_one(self):
self.results.insert(END, "(")
def bracket_two(self):
self.results.insert(END, ")")
def all_clear(self):
self.results.delete(0, END)
def clear(self):
self.results.delete(-1)
def multiplication(self):
self.results.insert(END, "*")
def division(self):
self.results.insert(END, "/")
def addition(self):
self.results.insert(END, "+")
def subtraction(self):
self.results.insert(END, "-")
def decimal_point(self):
self.results.insert(END, ".")
def about():
messagebox.showinfo(title = "About", message = "Author")
return
helpMenu = Menu(menubar)
menubar.add_command(label = "About", command=about)
if __name__ == '__main__':
Calculator().mainloop()
calculator.config(menu=menubar)
calculator.mainloop()
Your issue is that you are not associating the menubar with your root application. That is why it is never coming up. You need to configure the menu for your application to be the menubar you create. Example -
calculator.configure(menu=menubar)
Also, it would be better to move that code inside you frame as well. Example -
from tkinter import *
from tkinter import messagebox
calculator = Tk()
calculator.title("Calculator")
calculator.geometry("317x145")
menubar = Menu(calculator)
class Calculator(Frame):
def __init__(self):
Frame.__init__(self)
display = Frame(calculator, bd=0, width=1000, height=1000, relief=SUNKEN)
buttons = Frame(calculator, bd=0, width=7, height=1, relief=GROOVE)
display.grid(column=0, row=0, padx=0, pady=0)
buttons.grid(column=0, row=1, padx=1)
numbers = StringVar()
self.results = Entry(display, textvariable=numbers, width=31, fg="DarkOrchid4", bg="lavender blush", font="Verdana")
self.results.pack()
self.results.grid(column=0, row=0)
def showup(x):
return lambda: self.results.insert(END, x)
numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for i in range(9):
n=numbers[i]
Button(buttons, bg="snow", text=n, width=7, height=1, command=showup(n), relief=RAISED).grid(row=i%3, column=i//3)
Clear = Button(buttons, bg="snow", text="C", width=7, height=1, command=self.clear, relief=RAISED)
Clear.grid(padx=2, pady=2, column=3, row=0)
Equals = Button(buttons, bg="snow", text="=", width=7, height=1, command=self.equals, relief=RAISED)
Equals.grid(padx=2, pady=2, column=4, row=3)
All_clear = Button(buttons, bg="snow", text="AC", width=7, height=1, command=self.all_clear, relief=RAISED)
All_clear.grid(padx=2, pady=2, column=4, row=0)
Bracket_one = Button(buttons, bg="snow", text="(", width=7, height=1, command=self.bracket_one, relief=RAISED)
Bracket_one.grid(padx=2, pady=2, column=2, row=3)
Bracket_two = Button(buttons, bg="snow", text=")", width=7, height=1, command=self.bracket_two, relief=RAISED)
Bracket_two.grid(padx=2, pady=2, column=3, row=3)
Zero = Button(buttons, bg="snow", text="0", width=7, height=1, command=self.zero, relief=RAISED)
Zero.grid(padx=2, pady=2, column=0, row=3)
Decimal_point = Button(buttons, bg="snow", text=".", width=7, height=1, command=self.decimal_point, relief=RAISED)
Decimal_point.grid(padx=2, pady=2, column=1, row=3)
Multiplication = Button(buttons, bg="red", text="x", width=7, height=1, command=self.multiplication, relief=RAISED)
Multiplication.grid(padx=2, pady=2, column=3, row=1)
Division = Button(buttons, bg="powder blue", text="/", width=7, height=1, command=self.division, relief=RAISED)
Division.grid(padx=2, pady=2, column=4, row=1)
Addition = Button(buttons, bg="yellow", text="+", width=7, height=1, command=self.addition, relief=RAISED)
Addition.grid(padx=2, pady=2, column=3, row=2)
Subtraction = Button(buttons, bg="green", text="-", width=7, height=1, command=self.subtraction, relief=RAISED)
Subtraction.grid(padx=2, pady=2, column=4, row=2)
self.menubar = Menu(self)
def about():
messagebox.showinfo(title = "About", message = "Author")
return
self.helpMenu = Menu(self.menubar)
self.menubar.add_cascade(label="Help",menu=self.helpMenu)
self.helpMenu.add_command(label = "About", command=about)
calculator.config(menu=self.menubar)
def equals(self):
try:
result = eval(self.results.get())
except:
result = "Invalid input"
self.all_clear()
self.results.insert(0, result)
def zero(self):
self.results.insert(END, "0")
def bracket_one(self):
self.results.insert(END, "(")
def bracket_two(self):
self.results.insert(END, ")")
def all_clear(self):
self.results.delete(0, END)
def clear(self):
self.results.delete(-1)
def multiplication(self):
self.results.insert(END, "*")
def division(self):
self.results.insert(END, "/")
def addition(self):
self.results.insert(END, "+")
def subtraction(self):
self.results.insert(END, "-")
def decimal_point(self):
self.results.insert(END, ".")
if __name__ == '__main__':
Calculator().mainloop()
calculator.config(menu=menubar)
calculator.mainloop()