I try to add image in tkinter but it didn't show up but when I added label of text,the text show but the image didn't.Thank you
from tkinter import *
class window1:
def __init__(self, parent, word, geometry):
# image
bank_img = PhotoImage(file='C:\\Users\\user\\PycharmProjects\\pythonProject3\\bank-988164_640.png')
self.parent = parent
self.word = word
self.geometry = geometry
parent.geometry(geometry)
parent.title(self.word)
# Label
label = Label(parent, text="Welcome to the bank", height=3).pack()
bank_logo = Label(parent,image=bank_img).pack()
root = Tk()
app = window1(root, 'beginner bank system', '300x300')
Add root.mainloop() at the end.
root = Tk()
app = window1(root, 'beginner bank system', '300x300')
root.mainloop()
I have made a simple GUI that has two buttons for a Square function and Exit button. I want to print the results on the canvas as shown in the expected results.
Here are my codes
from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog
from PIL import Image, ImageTk
import os
import cv2
import numpy as np
import time
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command =Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
#Label widget
############################################################################################
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
My expected results are given in the image below
Not entirely sure what you are asking. But, if you just want to create text on canvas use canvas.create_text(x, y, text).
from tkinter import *
from PIL import Image,ImageTk
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command=self.Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
c_id = self.canvas.create_text(0, 20, text=f"{i}\t{y}", fill="blue", font="Times 14")
bbox = self.canvas.bbox(c_id)
self.canvas.coords(c_id, 100, bbox[3]*i)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
I need to add upload button so that I can upload the picture and display with this class. Everything working but when I am adding the upload button its giving me some error and my code is not wokring.
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.canvas = tk.Canvas(self.master)
self.canvas.pack()
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image)
self.loadbackground()
def loadbackground(self):
self.label = tk.Label(self.canvas, image = self.background)
self.label.bind('<Configure>',self.resizeimage)
self.label.pack(fill='both', expand='yes')
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((self.master.winfo_width(),self.master.winfo_height()))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()
Create the Button widget within the class constructor and bind it with self.loadbackground. Also, you don't need to recreate the Label widget every time instead use label.configure(image=yourimage).
Here is the code:
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.button = Button(self.master, text='Upload', command=self.loadbackground)
self.button.pack()
self.canvas = tk.Canvas(self.master)
self.canvas.pack(fill=BOTH, expand=True)
self.background_image = None
self.image_copy = None
self.background = None
self.label = tk.Label(self.canvas)
self.label.pack(fill='both', expand=True)
def loadbackground(self):
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image.resize((self.canvas.winfo_width(), self.canvas.winfo_height())))
self.label.configure(image=self.background)
self.label.bind('<Configure>',self.resizeimage)
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((event.width, event.height))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()
My plan is to provide a simple interface for the user to select an image. This is then used to perform an analysis.
The problem I have is this:
I can't get the connection between the GUI and the input of the rest of the code. CV2.imread only works when I directly specify the filename.
What is the best way to solve this problem?
Here is the code I am using:
import cv2
import numpy as np
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from tkinter import ttk
class Root (Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Tkinter First Window")
self.minsize(600,300)
self.labelFrame = ttk.LabelFrame(self, text = "Open a File")
self.labelFrame.grid()
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse a File", command = self.fileDialog)
self.button.grid()
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "C:\Python\Code\venv\Testbilder", title ="Select a File", filetype =(("jpeg", "*.jpg"), ("All Files", "*.*")))
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid()
self.label.configure(text = self.filename)
def main():
show_image = False
**image = cv2.imread("Testbild 3%.jpg")** **I need the connection here! This needs to be the input
blue_pixels_mask = cv2.inRange( from the GUI selection**
cv2.cvtColor(image, cv2.COLOR_BGR2HSV),
np.array([100, 50, 50]),
np.array([130, 255, 255]),
)
total_pixel_count = image.size // 3
if show_image:
cv2.imshow("Image", image)
cv2.imshow("Mask", blue_pixels_mask)
blue_pixel_count = cv2.countNonZero(blue_pixels_mask)
blue_ratio = blue_pixel_count / total_pixel_count
print(f"Das gesamte Bild besteht aus{total_pixel_count} Pixeln.")
print(f"Das Bild beinhaltet {blue_pixel_count} blaue Pixel.")
print(f"Der Blauanteil betrÃĪgt damit: {blue_ratio:0.2%}.")
if show_image:
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
root =Root()
root.mainloop()
I've got the following code:
import tkinter
import cv2
from PIL import Image, ImageTk
import threading
class HudGui:
def __init__(self, window):
# defining everything for video capture and the tkinter window
self.CapDev= cv2.VideoCapture(0)
self.cams = []
self.counter = 0
self.frame = None
self.panel = None
self.wind = window
btn = tkinter.Button(window, text="Snapshot!")
btn.pack(side="bottom", fill="both", expand="yes", padx=10, pady=10)
# defining threading for video stream
self.stopEvent = threading.Event()
self.thread = threading.Thread(target=self.videoLoop(), args=(1,))
self.thread.start()
def videoLoop(self):
while not self.stopEvent.is_set():
# reading and modifying the frame to have the proper data type
self.frame = self.CapDev.read()[1]
image = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
image = Image.fromarray(image)
image = ImageTk.PhotoImage(image)
if self.panel is None:
self.panel = tkinter.Label(image=image)
self.panel.image = image
self.panel.pack(side="left") # side="left", padx=10, pady=10
# otherwise, update the panel
else:
self.panel.configure(image=image)
self.panel.image = image
hud = tkinter.Tk()
hud.title("HUD")
HudGui(hud)
hud.mainloop()
When I run this code, nothing happens. I get no window but I do know it is updating the panel (I've tested it with printing messages). Could there be permissions problem for accessing the camera and things like that?
Project info:
Python = 3.7.3
opencv-contrib-python = 3.4.4.19