I would like to open an image when clicking a button with tkinter. According to the button, the image which is displayed is changing. So, the name of the button is the name of a dish and when the user click on it, it displays the image corresponding to the dish. (I'm taking the name of the dish from a database).
This is my code:
import sys
from tkinter import *
import tkinter as tk
from PIL import Image
class Application(tk.Frame):
x = 2
def __init__(self, param = None, i = None, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
if (self.x == 2):
param = "coucou"
self.hi_there = tk.Label(self)
self.hi_there["text"] = param
#self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
# Opening file in read format
File = open('data.txt',"r")
if(File == None):
print("File Not Found..")
else:
while(True):
# extracting data from records
record = File.readline()
if (record == ''): break
data = record.split(',')
print('Name of the dish:', data[0])
self.hi_there = tk.Button(self)
self.hi_there["text"] = data[0]
self.hi_there["command"] = self.photoOfTheDish
self.hi_there.pack(side="top")
# printing each record's data in organised form
for i in range(1, len(data)):
print('Ingredients:',data[i])
self.hi_there = tk.Label(self)
self.hi_there["text"] = data[i]
self.hi_there.pack(side="top")
File.close()
def photoOfTheDish(self):
#i = "0.ppm"
novi = Toplevel()
canvas = Canvas(novi, width = 1500, height = 1000)
canvas.pack(expand = YES, fill = BOTH)
with open('data.txt') as f:
count = sum(1 for _ in f)
print(count)
for i in range(count):
print(i)
gif1 = PhotoImage(file = str(i) + ".ppm")
#image not visual
canvas.create_image(50, 10, image = gif1, anchor = NW)
#assigned the gif1 to the canvas object
canvas.gif1 = gif1
root = tk.Tk()
root.geometry("5000x2000")
app = Application(master=root)
app.mainloop()
The important part of my code for this issue is here:
with open('data.txt') as f:
count = sum(1 for _ in f)
print(count)
for i in range(count):
print(i)
gif1 = PhotoImage(file = str(i) + ".ppm")
#image not visual
canvas.create_image(50, 10, image = gif1, anchor = NW)
#assigned the gif1 to the canvas object
canvas.gif1 = gif1
So I want to open images named "0.ppm", "1.ppm", "2.ppm"... that is why I created a counter so I have "i.ppm" with i going from 0 to the number of lines in my database.
My problem is: when I click on a button, the image displayed is not the image of the selected dish, it's always the image of the last dish because i is going straight away to the final number of lines. But I want it to display the right image according to the right dish.