Related
So as i have already posted a few questions here, about this assignment i have to do for uni, that is about building a food recipes desktop app with Tkinter and Python. And i thought it would be nice to add some kind of a random horizontal scroll/roulette selector of recipes in this bar that i am insert at the bottom of the startpage:
Like whenever the user clicked in one of the arrows (right or left) it would roll horizontally different recipe buttons and after some secons it would stop, something like a roulette I think:
Is that even possible to make with Tkinter and Python? I have already put the recipes buttons inside a main canvas, that would hide, on its sides, the others buttons that are not appearing at the moment. And i would probably need to do some function to when either one of the arrows was clicked it would do the "random selector thing". But what do i need to have inside the function? Thank you!!
Here's the code that i have already have for the bar:
self.c_randombar = Canvas(self, width=1078, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
self.c_randombar.place(x=181, y=906,)
self.img_random = PhotoImage(file="assets/frame0/randomrecipe.png")
self.c_randombar.create_image(0, 0,anchor="nw", image= self.img_random)
#Right Arrow
self.c_rightarrow = Canvas(self, width=81, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
self.c_rightarrow.place(x=1290, y=907,)
self.img_bg_rightarrow = PhotoImage(file="assets/frame0/bg_rightarrow.png")
self.c_rightarrow.create_image(0, 0,anchor="nw", image= self.img_bg_rightarrow)
#---------
self.img_rightarrow = PhotoImage(file = r"assets/frame0/button_rightarrow.png")
self.button_rightarrow = tk.Button(self, image = self.img_rightarrow, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,)
self.button_rightarrow.place(x=1289, y=906, width=81, height=64)
#Left Arrow
self.c_leftarrow = Canvas(self, width=81, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
self.c_leftarrow.place(x=71, y=907,)
self.img_bg_leftarrow = PhotoImage(file="assets/frame0/bg_rightarrow.png")
self.c_leftarrow.create_image(0, 0,anchor="nw", image= self.img_bg_leftarrow)
#---------
self.img_leftarrow = PhotoImage(file = r"assets/frame0/button_leftarrow.png")
self.button_leftarrow = tk.Button(self, image = self.img_leftarrow, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,)
self.button_leftarrow.place(x=70, y=906, width=81, height=64)
#____________________________
#Main Canvas for the recipes buttons
self.c_recipes = Canvas(self, width=1074, height=60, borderwidth=0, highlightthickness=0,relief="flat", background="#182DEF")
self.c_recipes.place(x=183, y=908)
#Recipe 1
self.c_recipe1 = Canvas(self.c_recipes, width=157, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
self.c_recipe1.place(x=40, y=17,)
self.img_bg_recipe1 = PhotoImage(file="assets/frame0/Nova pasta/bg_button1.png")
self.c_recipe1.create_image(0, 0,anchor="nw", image= self.img_bg_recipe1)
#---------
self.img_recipe1 = PhotoImage(file = r"assets/frame0/Nova pasta/button1.png")
self.button_recipe1 = tk.Button(self.c_recipes, image = self.img_recipe1, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
self.button_recipe1.place(x=39, y=16, width=157, height=27)
#____________________________
#Recipe 2
self.c_recipe2 = Canvas(self.c_recipes, width=256, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
self.c_recipe2.place(x=340, y=17,)
self.img_bg_recipe2 = PhotoImage(file="assets/frame0/Nova pasta/bg_button2.png")
self.c_recipe2.create_image(0, 0,anchor="nw", image= self.img_bg_recipe2)
#---------
self.img_recipe2 = PhotoImage(file = r"assets/frame0/Nova pasta/button2.png")
self.button_recipe2 = tk.Button(self.c_recipes, image = self.img_recipe2, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
self.button_recipe2.place(x=339, y=16, width=256, height=27)
#____________________________
#Recipe 3
self.c_recipe3 = Canvas(self.c_recipes, width=296, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
self.c_recipe3.place(x=739, y=17,)
self.img_bg_recipe3 = PhotoImage(file="assets/frame0/Nova pasta/bg_button3.png")
self.c_recipe3.create_image(0, 0,anchor="nw", image= self.img_bg_recipe3)
#---------
self.img_recipe3 = PhotoImage(file = r"assets/frame0/Nova pasta/button3.png")
self.button_recipe3 = tk.Button(self.c_recipes, image = self.img_recipe3, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
self.button_recipe3.place(x=738, y=16, width=296, height=27)
#____________________________```
Forever thankful!!
I have a program that allows the user to select an image from their PC and then displays it. The problem is that it only works once. The first photo is displayed but if I select/open another, I would think that this photo would then appear on top of the original but it doesn't.
Any idea why?
root = tk.Tk()
root.geometry("500x500")
root.title('Color Comparer')
picture_chooser_btn = tk.Button(master=root, text='Select Image', command= lambda: open_image())
picture_chooser_btn.pack()
base_color_picker_btn = tk.Button(master=root, text='Choose Base Color', command= lambda: selectBaseColor())
base_color_picker_btn.pack()
canvas = Canvas(root, width=80, height=50, bg="#F8F9F9")
base_color_rect = canvas.create_rectangle(0, 0, 85, 85, fill="red")
canvas_label = canvas.create_text((42, 20), text="Base Color")
canvas.pack()
label = tk.Label(root, anchor="w")
label.pack(side="top", fill="x")
root.bind('<ButtonPress-1>', on_click)
root.mainloop()
The function used to grab the photo from PC:
def open_image():
global image_selected
path=filedialog.askopenfilename(filetypes=[("Image File",'.jpg .png .jpeg')])
im = Image.open(path)
im = im.resize((400, 400), Image.ANTIALIAS)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.lift()
label.configure(text="you selected an image")
print("you selected an image")
print(str(tkimage))
image_selected = True
You need to destroy the old label widget containing the previous image before you can display a new one.
I made some minor modifications to your function that allows the code to work as you described
myvar = None
def open_image():
global myvar
if myvar is not None:
myvar.destroy()
path=filedialog.askopenfilename(filetypes=[("Image File",'.jpg .png .jpeg')])
im = Image.open(path)
im = im.resize((400, 400), Image.ANTIALIAS)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.lift()
label.configure(text="you selected an image")
print("you selected an image")
print(str(tkimage))
I was making python gui with tkinter
I wanted to change button's image if I push button
But it doesn't work.(I use config)
with some effort I found it work in main code
but still it doesn't work in fucntion that is connected to button
Here are the codes
from tkinter import *
from PIL import Image, ImageTk
# using by function
def select_precision():
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
def image_resize(size, link):
image = Image.open(link)
image = image.resize(size, Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
return image
root = Tk()
root.title()
precision = PhotoImage(file="gui_project/item_simulation/precision.png")
rune00 = PhotoImage(file="gui_project/item_simulation/domination.png")
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
runepage_precision.pack()
runepage_00.pack()
root.mainloop()
but if I change like this, the config works but I don't know why
from tkinter import *
from PIL import Image, ImageTk
def image_resize(size, link):
image = Image.open(link)
image = image.resize(size, Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
return image
root = Tk()
root.title()
precision = PhotoImage(file="gui_project/item_simulation/precision.png")
rune00 = PhotoImage(file="gui_project/item_simulation/domination.png")
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
# using inside the code
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
runepage_precision.pack()
runepage_00.pack()
root.mainloop()
to make it short
first was
def select_precision():
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
and second was
runepage_precision = Button(root, width=20, height=20,\
image=precision, command=select_precision)
runepage_00 = Button(root, width=20, height=20, image=rune00)
overheal = image_resize((20, 20), "gui_project/item_simulation/overheal.png")
runepage_00.config(image=overheal)
I mean a scroll bar that would allow you to preview the next operations. I will include lines for this example and a pictorial image. Referring to another topic and trying to solve it, I have a question. Dante would not describe what is happening in the development environment and it's hard to see without a map.
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from PIL import ImageTk
import cv2
import os
import numpy as np
history = [] # image:im , "process": p1|p2|cvt|inv|canny|... or what you want }
def showImage(canvas):
im_canvas = Image.fromarray(canvas)
imtk_canvas = ImageTk.PhotoImage(im_canvas)
lbl = Label(image=imtk_canvas)
lbl.image = imtk_canvas
lbl.pack(side="left", padx=8, pady=8)
def fSave():
savepath = filedialog.asksaveasfilename()
cv2.imwrite(savepath, history[-1]["image"])
def fOpen():
if len(history) > 0:
history.clear()
print(history)
openpath = filedialog.askopenfilename()
if os.path.isfile(openpath):
canvas = cv2.imread(openpath)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0, ({"image": canvas, "process": "openfile"}))
showImage(canvas)
else:
messagebox.showerror(
title="File open Error", message="The file does not exists!")
def func1():
canvas = history[0]["image"] # i tried 0 or -
print("from history type,shape ", type(canvas), canvas.shape)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY)
canvas = cv2.Canny(canvas, 30, 70)
# history.insert(0, ({"image": im2, "process": "func1"}))
history.insert(0,({"image": canvas, "process": "func1"}))
#history.append({"image": canvas, "process": "func1"})
showImage(canvas)
def func2():
canvas = history[0]["image"]
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
canvas = 255 - canvas
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0,({"image": canvas, "process": "func2"}))
showImage(canvas)
def set_scrollregion(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
def ini():
root = Tk()
canvas = Canvas(root)
canvas.pack(side=TOP, fill=BOTH, expand=TRUE)
xscrollbar = Scrollbar(root, orient=HORIZONTAL, command=canvas.xview)
xscrollbar.pack(side=BOTTOM, fill=X)
canvas.configure(xscrollcommand=xscrollbar.set)
frame = Frame(canvas)
canvas.create_window((0, 0), window=frame, anchor=NW)
frame.bind('<Configure>', set_scrollregion)
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load", command=fOpen)
filemenu.add_command(label="Save", command=fSave)
filemenu.add_command(label="func1", command=func1)
filemenu.add_command(label="func2", command=func2)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
if __name__ == '__main__':
ini()
I have studied the topic, I have dug up half of the internet, documentation and there is progress, but I usually try to eliminate bugs. So that it could be scrolled sideways.
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from PIL import ImageTk
import cv2
import os
import numpy as np
history=[] #image:im , "process": p1|p2|cvt|inv|canny|... or what you want }
def showImage(canvas,lbl,side="left"):
im_canvas = Image.fromarray(canvas)
imtk_canvas = ImageTk.PhotoImage(im_canvas)
'''
lbl = Label(image=imtk_canvas)
lbl.image = imtk_canvas
lbl.pack(side="left", padx=8, pady=8)
'''
lbl.image = imtk_canvas
lbl.configure(image=imtk_canvas)
lbl.pack(side="left", padx=8, pady=8)
def fSave():
savepath = filedialog.asksaveasfilename()
cv2.imwrite(savepath, history[-1]["image"])
def fOpen(lbl,lbox):
openpath = filedialog.askopenfilename()
if os.path.isfile(openpath):
canvas = cv2.imread(openpath)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
hid = len(history)
history.append({"image":canvas,"process":"fOpen"})
lbox.insert(END, f"HistoryID:{hid} - fOpen:{openpath}")
lbox.pack()
showImage(canvas,lbl,"bottom")
else:
messagebox.showerror(
title="File open Error" , message="The file does not exists!")
def func1(lbl,lbox):
canvas = history[-1]["image"]
print("from history type,shape ",type(canvas),canvas.shape)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY)
canvas = cv2.Canny(canvas, 30, 70)
hid = len(history)
history.append({"image":canvas,"process":"func1"})
lbox.insert(END, f"HistoryID:{hid} - func1")
lbox.pack()
showImage(canvas,lbl)
def func2(lbl,lbox):
canvas = history[-1]["image"]
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
canvas = 255 - canvas
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
hid = len(history)
history.append({"image":canvas,"process":"func2"})
lbox.insert(END, f"HistoryID:{hid} - func2")
lbox.pack()
showImage(canvas,lbl)
def ini():
root = Tk()
lbox = Listbox(root, width = 640, height = 5 )
lbox.pack()
lbl1 = Label(root)
lbl1.pack()
lbl2 = Label(root)
lbl2.pack()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load", command=lambda:fOpen(lbl1,lbox))
filemenu.add_command(label="Save", command=fSave)
filemenu.add_command(label="func1", command=lambda:func1(lbl2,lbox))
filemenu.add_command(label="func2", command=lambda:func2(lbl2,lbox))
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
if __name__ == '__main__':
ini()
In this example you can change the image of the same Label ...
# It would be better to open new questions with new posts to address different problems.
from somewhere on Stack Overflow (sorry)
import tkinter as tk
from PIL import Image
from PIL import ImageTk
path1='images/test1.png'
path2='images/test2.png'
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path1))
panel = tk.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
def callback(e):
img2 = ImageTk.PhotoImage(Image.open(path2))
panel.configure(image=img2)
panel.image = img2
root.bind("<Return>", callback)
root.mainloop()
I mean a scroll bar that would allow you to preview the next operations. I will include lines for this example and a pictorial image. Dante would not describe what is happening in the development environment and it's hard to see without a map.
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from PIL import ImageTk
import cv2
import os
import numpy as np
history = [] # image:im , "process": p1|p2|cvt|inv|canny|... or what you want }
def showImage(canvas):
im_canvas = Image.fromarray(canvas)
imtk_canvas = ImageTk.PhotoImage(im_canvas)
lbl = Label(image=imtk_canvas)
lbl.image = imtk_canvas
lbl.pack(side="left", padx=8, pady=8)
def fSave():
savepath = filedialog.asksaveasfilename()
cv2.imwrite(savepath, history[-1]["image"])
def fOpen():
if len(history) > 0:
history.clear()
print(history)
openpath = filedialog.askopenfilename()
if os.path.isfile(openpath):
canvas = cv2.imread(openpath)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0, ({"image": canvas, "process": "openfile"}))
showImage(canvas)
else:
messagebox.showerror(
title="File open Error", message="The file does not exists!")
def func1():
canvas = history[0]["image"] # i tried 0 or -
print("from history type,shape ", type(canvas), canvas.shape)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY)
canvas = cv2.Canny(canvas, 30, 70)
# history.insert(0, ({"image": im2, "process": "func1"}))
history.insert(0,({"image": canvas, "process": "func1"}))
#history.append({"image": canvas, "process": "func1"})
showImage(canvas)
def func2():
canvas = history[0]["image"]
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
canvas = 255 - canvas
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0,({"image": canvas, "process": "func2"}))
showImage(canvas)
def ini():
root = Tk()
h = Scrollbar(root, orient='horizontal')
h.pack(side=BOTTOM, fill=X)
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load", command=fOpen)
filemenu.add_command(label="Save", command=fSave)
filemenu.add_command(label="func1", command=func1)
filemenu.add_command(label="func2", command=func2)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
if __name__ == '__main__':
ini()
sample effect image
I'm new in GUI developing.Here i'hv created two GUI, one for taking photo and another for showing features.so,i'hv used two functions.but i don't know some things.Now i need two kinds of help from you.
1)what is the command for printing float value in GUI(not on console)?
2)How to calculate the value of mean,variance ,s.d. etc from a image and how to pass those values from one function to another function?
import tkinter as tk
from tkinter.filedialog
import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print some features of image e.g. Mean, variance,s.d. Etc.
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
dirPath = " "
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
#this is the image
Photo = Image.open(fileName)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
Okay, I took some more time to look into it.
Concerning the calculation of the values, your previous question did that correct, however the variables needed to be accessible globally. Concerning the displaying of a text, you have to add a tkinter text widget. If you want to add more calculated values, just google for numpy + 'value your want'.
I've taken your code and created a working example, see the code below. Note that I removed some stuff that wasn't neede for the example, so copy the lines you need to your own code. Also check out this reference for the text widget.
Result:
Code:
Note: I created 2 text widgets deliberately, to show 2 ways of implementing multiple texts
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
### create a text widget, place it in window1 and insert the text
width_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
width_txt.grid(column=0, row=0)
width_txt.insert(tk.END, "Width: " + str(width))
height_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
height_txt.grid(column=0, row=1)
height_txt.insert(tk.END, "Height: " + str(height) + "\nMean: " + str(mean))
window1.geometry("650x510")
window1.configure(background="lightgreen")
def openphoto():
### this line makes the variables accessible everywhere
global width,height, mean
import numpy as np
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
photo = Image.open(fileName)
#### calculate values
height = np.size(photo, 0)
width = np.size(photo, 1)
mean = np.mean(photo)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()