resizing image in tkinter for my browsing file code - python-3.x

how can I resize my image? here is my code..
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk
class Root(Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Python Tkinter Dialog Widget")
self.minsize(640, 400)
self.labelFrame = ttk.LabelFrame(self, text = "Open File")
self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select A File", filetype =
(("jpeg files","*.jpg"),("all files","*.*")) )
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
img = Image.open(self.filename)
photo = ImageTk.PhotoImage(img)
self.label2 = Label(image=photo)
self.label2.image = photo
self.label2.grid(column=3, row=4)
root = Root()
root.mainloop()

You can either use Image.resize() which does not keep the image aspect ratio, or Image.thumbnail() which keeps the image aspect ratio:
img = Image.open(self.filename)
imgsize = (600, 400) # change to whatever size you want
#img = img.resize(imgsize)
img.thumbnail(imgsize)
photo = ImageTk.PhotoImage(img)

Related

How can I scroll multiple frames in canvas?

I want to create a list of frames with further features like a button, label e.g.. but my issues are the size of the LabelFrame. If I put the LabelFrame in container it fits like I want to but it isn't scrollable any more. Any ideas?
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
container = ttk.Frame(root)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
for i in range(50):
lf = ttk.Frame(scrollable_frame, text=i).grid(column=1, row=i)
frame_ip = tk.LabelFrame(lf, bg="white", text=i)
frame_ip.place(relwidth=0.95, relheight=0.2, relx=0.025, rely=0)
button_scroll1 = tk.Button(frame_ip, text="Start", bg="grey")
button_scroll1.place(relwidth=0.15, relx=0.025, relheight=0.15, rely=0.1)
container.pack()
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
root.mainloop()
Here is your updated code with a Button, Canvas and Scrollbar inserted into each LabelFrame with grid manager.
I've also made the container resizable with row|column configure.
Seems to work fine.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
root.geometry("341x448")
container = ttk.Frame(root)
container.rowconfigure(0, weight = 1)
container.columnconfigure(0, weight = 1)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient = tk.VERTICAL, command = canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window = scrollable_frame, anchor = tk.NW)
canvas.configure(yscrollcommand = scrollbar.set)
for i in range(15):
L = ttk.LabelFrame(scrollable_frame, text = "Sample scrolling label")
L.grid(row = i, column = 0, sticky = tk.NSEW)
B = ttk.Button( L, text = f"Button {i}")
B.grid(row = 0, column = 0, sticky = tk.NW)
K = tk.Canvas(
L, width = 300, height = 100,
scrollregion = "0 0 400 400", background = "#ffffff")
K.grid(row = 1, column = 0, sticky = tk.NSEW)
S = ttk.Scrollbar( L, command = K.yview)
S.grid(column = 1, row = 1, sticky = tk.NSEW)
K["yscrollcommand"] = S.set
container.grid(row = 0, column = 0, sticky = tk.NSEW)
canvas.grid(row = 0, column = 0, sticky = tk.NSEW)
scrollbar.grid(row = 0, column = 1, sticky = tk.NS)
root.mainloop()

Why does my Tkinter window crash when I try to display a label?

I am using Pycharm and Python 3.8.
My Tkinter window stops responding and causes my program to crash.
Pycharm presents the following line in its output: Process finished with exit code -805306369 (0xCFFFFFFF)
I have the following code for displaying the progress of a for loop:
import tkinter as tk
from tkinter import filedialog, ttk
from tkinter.ttk import Progressbar
import json
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.filename = ''
tk.Button(self, text = 'Upload File', command = self.get_file).grid(row = 0, column = 0)
tk.Button(self, text = 'Verify', command = self.verify).grid(row = 1, column = 0)
# tk.Label(self, text = 'some name').grid(row = 0, column = 1)
self.mainloop()
def get_file(self):
self.filename = tk.filedialog.askopenfilename(title = "Select File", filetypes = [("JSON", "*.json")])
tk.Label(self, text = self.filename).grid(row = 0, column = 1)
def verify():
lbl = tk.Label(self, text = 'Verifying Trustee Public Keys')
lbl.grid(row = 2, column = 0)
prog1 = ttk.Progressbar(self,
length = 100,
orient = "horizontal",
maximum = len(self.data["trustee_public_keys"]),
value = 0)
prog1.grid(row = 3, column = 0)
i = 1
for trustee_key_list in self.data['trustee_public_keys']:
print('Trustee :', i)
//some code
i = i+1
prog1['value'] = i
The get_file part works. But, when I click the verify button to execute the verify() function. The entire window freezes and I get a not responding message.
WHat is the problem with the following part of my code?
lbl = tk.Label(self, text = 'Verifying Trustee Public Keys')
lbl.grid(row = 2, column = 0)
What am I doing wrong?

AttributeError: 'NoneType' object has no attribute 'read'.How to fix this error?

Traceback errorimport tkinter
import PIL
from tkinter import *
import tkinter.ttk as ttk;
from ttk import *
from tkinter import filedialog
from PIL import ImageTk, Image
class Root(Tk):
def init(self):
super(Root, self).init()
self.title("Brain Tumor Detection Using Deep learning")
self.minsize(400, 200)
# self.wm_iconbitmap('icon.ico')
self.labelFrame = ttk.LabelFrame(self, text = "Choose Here")
self.labelFrame.grid(column = 0, row = 5, padx = 150, pady = 150)
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse A File",command=self.open_img)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select A File", filetype =
(("jpeg files","*.jpg"),("all files","*.*")) )
print(self.filename)
#print(self.filename)
#photo = PhotoImage(self.filename)
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
``def open_img(self):
# Select the Imagename from a folder
x = self.fileDialog()
# print(x)
# opens the image
img = Image.open(x)
# resize the image and apply a high-quality down sampling filter
img = img.resize((250, 250), Image.ANTIALIAS)
# PhotoImage class is used to add image to widgets, icons etc
img = ImageTk.PhotoImage(img)
#imgs = Label(self, image=img)
#imgs.image = img
# create a label
panel = Label(root, image = img)
# set the image as img
panel.image = img
panel.grid(row = 2)

How to scroll contents in label?

I want to scroll contents in a label. I'm a begginer. Please help me.
I did it like below.But it doesn't working. I found this from the internet. But it doesn't working. I take some data from a .txt file and i need to display in a lable. The lable is not enough to display them all. So I need to scroll the contents in the label.
from tkinter import ttk
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
window=tk.Tk()
im = Image.open("landscape2.png")
tkimage = ImageTk.PhotoImage(im)
tab_control = ttk.Notebook(window)
tab5 = ttk.Frame(tab_control)
tab_control.add(tab5, text='History')
tab_control.pack(expand=1, fill='both')
his_lbl = tk.Label(tab5, image=tkimage)
his_lbl.place(relwidth = 1, relheight = 1)
his_frame = tk.Frame(tab5, bg='#80c1ff',bd=5)
his_frame.place(relx = 0.3, rely = 0.1, relheight=0.1, relwidth=0.50,
anchor= 'n')
button = tk.Button(his_frame, bg = 'white', command = lambda:
get_weather(his_entry.get()))
button.place(relx = 0.7, relheight = 1, relwidth = 0.3)
his_entry = tk.Entry(his_frame, font =('Courier', 18))
his_entry.place(relheight = 1, relwidth = 0.65)
canvas = Canvas(tab5, bg="white")
canvas.place(relx = 0.3, rely = 0.25, relheight = 0.6, relwidth = 0.50,
anchor='n')
lst = []
y = 0
label = Label(canvas,anchor='w', font=("Courier", 20),
compound=RIGHT,bg='white',bd=4, justify="left")
label.place(relwidth=1,relheight=1)
canvas.create_window(0, y, window=label, anchor=NW)
y += 60
scrollbar = Scrollbar(canvas, orient=VERTICAL, command=canvas.yview)
scrollbar.place(relx=1, rely=0, relheight=1, anchor=NE)
canvas.config(yscrollcommand=scrollbar.set, scrollregion=(0, 0, 0, y))
def get_weather(history):
file=open((history+".txt"),("r"))
a=(file.read())
label['text'] = a
window.mainloop()
What you are trying to do with a Canvas just to make a Label scrollable is an overkill in my opinion. You could use a Text widget instead and set its state to disabled to prevent the user from editing its content.
import tkinter as tk
root = tk.Tk()
# create text widget
text = tk.Text(root, background=root.cget('background'), relief='flat', height=10)
# insert text
content = "Long text to display\n" * 20
text.insert('1.0', content)
# disable text widget to prevent editing
text.configure(state='disabled')
# scrolling
scroll = tk.Scrollbar(root, orient='vertical', command=text.yview)
text.configure(yscrollcommand=scroll.set)
scroll.pack(side='right', fill='y')
text.pack(side='left', fill='both', expand=True)
root.mainloop()

How to show multiple pictures in tkinter with function?

I want to show many pictures in my gui application. But according to Here I need to save those pictures as reference to my class. but I am confused how should I do it with many pictures?
This does not show any image on the opened Window
from tkinter import *
import tkinter
import os
from PIL import Image, ImageTk
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) + "/"
class GUI():
def __init__(self,file_list):
self.file_list = file_list
self.root=Tk()
self.canvas = Canvas(self.root, width=480, height=800)
self.canvas.pack()
def image_opener(self, filename):
opened_image = Image.open(CURRENT_DIR + "images/gui/" + filename)
photo_image = ImageTk.PhotoImage(opened_image)
return photo_image
def show_image1(self):
img = self.image_opener(files["img1"])
self.canvas.create_image(0, 0, image=img, anchor = NW, state = NORMAL)
def show_image2(self):
img = self.image_opener(files["img2"])
self.canvas.create_image(0, 0, image=img, anchor = NW, state = NORMAL)
def show_screens(self):
self.show_image1()
self.show_image2()
self.root.mainloop()
files = {
"img1":"image1.png",
"img2":"image2.png",
"img3":"image3.png",
"img4":"image4.png"
}
gui = GUI(files)
gui.show_screens()
When I change it to this it shows pictures in the window but is there any elegant way to do it with many pictures (maybe around 75) ?
from tkinter import *
import tkinter
import os
from PIL import Image, ImageTk
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) + "/"
class GUI():
def __init__(self,file_list):
self.file_list = file_list
self.root=Tk()
self.canvas = Canvas(self.root, width=480, height=800)
self.canvas.pack()
self.opened_image1 = Image.open(CURRENT_DIR + "images/gui/image1")
self.photo_image1 = ImageTk.PhotoImage(self.opened_image1)
self.opened_image2 = Image.open(CURRENT_DIR + "images/gui/image2")
self.photo_image2 = ImageTk.PhotoImage(self.opened_image2)
def show_image1(self):
self.canvas.create_image(0, 0, image=self.photo_image1, anchor = NW, state = NORMAL)
def show_image2(self):
self.canvas.create_image(0, 0, image=self.photo_image2, anchor = NW, state = NORMAL)
def show_screens(self):
self.show_image1()
self.show_image2()
self.root.mainloop()
files = {
"img1":"image1.png",
"img2":"image2.png",
"img3":"image3.png",
"img4":"image4.png"
}
gui = GUI(files)
gui.show_screens()

Resources