PIL/tkinter - updating label image with button images - python

I'm trying to implement my simple image viewer, where I have one main label and menubutton with three choices. Each of them creates different numbers of buttons with pictures inside them. I would like create one main label and then update its image with images on the buttons. So when I click on the first button with image, that image will appear on the label, then click second button and that second image will appear and so on. I've tried to create two functions one for creating label and updating its image and the second for getting current image on the button, but I wasn't able to do the second one correctly. Appreciate your help. Here's the code:
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
from functools import partial
from PIL import Image, ImageTk
class Halabala():
def __init__(self):
self.master = tk.Tk()
self.master.geometry("1100x700")
self.pictures = ["pavuk1.gif", "pavuk2.gif", "pavuk3.gif"]
self.pictures2 = ["cukor1.gif", "cukor2.gif", "cukor3.gif", "cukor4.gif", "cukor5.gif"]
self.lists_images = []
self.lists_images2 = []
self.init_image_list()
self.lists_labels = []
#self.main_label = tk.Label(self.master, image = None).grid(row = 0, column = 0)
#image with original size
self.rbutton = tk.Menubutton(self.master, text = "Choose picture")
self.picks2 = tk.Menu(self.rbutton)
self.rbutton.config(menu=self.picks2)
self.picks2.add_command(label = "Spider", command = partial(self.create_labels,3))
self.picks2.add_command(label = "Sugar", command = partial(self.create_labels,5))
self.rbutton.config(width = 30, bg = "white", bd = 5, relief = tk.RAISED)
self.rbutton.place(x = 900, y = 30)
self.master.mainloop()
def init_image_list(self):
for i in self.pictures:
picture = Image.open(i)
picture.thumbnail((130, 130))
self.lists_images.append(ImageTk.PhotoImage(picture))
for i in self.pictures2:
picture = Image.open(i)
picture.thumbnail((130, 130))
self.lists_images2.append(ImageTk.PhotoImage(picture))
def create_labels(self, num):
for label in self.lists_labels:
label.destroy()
self.lists_labels=[]
for i in range(num):
if num == 3:
but = tk.Button(self.master, image = self.lists_images[i]) #command = self.get_command
but.grid(row = 2, column = i + 1) #label will be in the first row
self.lists_labels.append(but)
else:
but = tk.Button(self.master, image = self.lists_images2[i])
but.grid(row = 2, column = i + 1)
self.lists_labels.append(but)
#def get_command(self):
#self.main_label = tk.Label(self.master, image = self.get_image).grid(row = 0, column = 0)
#def get_image(self):
# don't know how to get current image from button
myapp = Halabala()

Related

How to make a image viewer with left right functionality in tkinter?

I have bunch of links and labels in list to view those I want to make a image viewer with next, previous functionality. My links and labels for respective images are in list. Up to now I had tried this :
urls=[url,url1,url2,url3]
labels=["label 1","label 2","label 3","label 4"]
images=[]
for ur in urls:
raw_data = urllib.request.urlopen(ur).read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
images.append(image)
Now I have images ready in images and now I want to display it in image viewer but only last image is visible in image viewer.
Label(root).grid(row=1,column=1)
for i in range(len(images)):
image_label=Label(root,image=images[i])
image_label.grid(row=1,column=2)
name=Label(root,text=labels[i])
name.grid(row=2,column=2)
def left():
image_label=Label(root,image=images[i-1])
image_label.grid(row=1,column=2)
def right():
image_label=Label(root,image=images[i+1])
image_label.grid(row=1,column=2)
left_button=Button(root,text="Left",command=left)
left_button.grid(row=2,column=1)
right_button=Button(root,text="Right",command=right)
right_button.grid(row=2,column=3)
Right button is not working and left button is working but for one time only. When I click left button second time then nothing is working.
Error while clicking in right button :
line 45, in right
image_label=Label(root,image=images[i+1])
IndexError: list index out of range
The code is pretty close to original posted example.
There is no lambda in Button, just straight forward command that gives access to left and right functions.
The name label is unnecessary as label objects already have a text attribute so I've integrated image and text into single label and increased the font size.
label compound is used to control where the image is display relative to the text, I've chosen top. That is, the image will be place above the text.
The use of global in functions keeps track of count
from tkinter import Tk, Label, Frame, Button
from PIL import ImageTk, Image
import io
import requests
import urllib
root = Tk()
urls = [url, url1, url2, url3]
labels = ["label 1","label 2","label 3","label 4"]
count = -1
images = []
for ur in urls:
raw_data = urllib.request.urlopen( ur ).read()
im = Image.open(io.BytesIO( raw_data ))
image = ImageTk.PhotoImage(im)
images.append(image)
def left( ):
global count
count = (count - 1) % len(images)
image_label.config(image = images[count], text = labels[count])
def right( ):
global count
count = (count + 1) % len(images)
image_label.config(image = images[count], text = labels[count])
image_label = Label(
root, image = images[count], font = "Helvetica 20 normal",
text = labels[count], compound = "top")
image_label.grid(row = 0, column = 0, columnspan = 2, sticky = "nsew")
Button(
root, text = "<< LEFT", command = left).grid( row = 1, column = 0, sticky = "ew")
Button(
root, text = "RIGHT >>", command = right).grid(row = 1, column = 1, sticky = "ew")
right( ) # display first image
root.mainloop()
Here's a way to do it by showing and hiding pairs of Labels with the image and it name on them. For development and testing purposes, it loads the images from disk instead of downloading them, but you can easily replace that with what you have in your question.
from pathlib import Path
from PIL import Image, ImageTk
from tkinter import Button, Tk, Label
root = Tk()
root.title('Image Viewer')
# Create thumbnails of all the images.
image_folder = '/path/to/image/folder'
images = []
for filepath in Path(image_folder).iterdir():
img = Image.open(filepath)
w, h = img.size
if w > h:
f = 100 / w
nw, nh = 100, int(f*h)
else:
f = 100 / h
nw, nh = int(f*w), 100
# Offsets to center thumbnail within (100, 100).
woff, hoff = (100-nw) // 2, (100-nh) // 2
img = img.resize((nw, nh), Image.BICUBIC) # Shrink so largest dimen is 100.
thumbnail = Image.new('RGBA', (100, 100), (255, 255, 255, 0)) # Blank.
thumbnail.paste(img, (woff, hoff)) # Offset keep it centered.
images.append(ImageTk.PhotoImage(thumbnail))
names = ['Name 1', 'Name 2', 'Name 3', 'Name 4']
def get_images():
"""Create all image and name Label pairs but initially hidden."""
global image_labels, name_labels
image_labels, name_labels = [], []
for i, (img, name) in enumerate(zip(images, names)):
image_label = Label(root, image=img)
image_label.grid(row=1, column=2)
image_labels.append(image_label)
name_label = Label(root, text=name)
name_label.grid(row=2, column=2)
name_labels.append(name_label)
hide(i)
def hide(i):
"""Hide specified image and name pair."""
image_labels[i].grid_remove()
name_labels[i].grid_remove()
def show(i):
"""Unhide specified image and name pair."""
image_labels[i].grid()
name_labels[i].grid()
def shift(direction):
"""Display the image and pair before or after the current one that is
`direction` steps away (usually +/-1).
"""
global current
hide(current)
current = (current + direction) % len(images)
show(current)
left_button = Button(root, text="Left", command=lambda: shift(-1))
left_button.grid(row=2, column=1)
right_button = Button(root, text="Right", command=lambda: shift(+1))
right_button.grid(row=2, column=3)
get_images()
current = 0 # Currently displayed image.
show(current)
root.mainloop()
Screenshot of it running:
Should just update a image label when shift left or right, not create a new label.
Using modulus % to find which one next turn.
To reduce code and executable, I use the image data in PySimpleGUI and simple name for image here.
import tkinter as tk
import PySimpleGUI as sg
def shift(num):
global index
index = (index + num) % size
label1.configure(image=images[index])
label2.configure(text =labels[index])
root = tk.Tk()
images = [tk.PhotoImage(data=image) for image in sg.EMOJI_BASE64_HAPPY_LIST]
size = len(images)
labels = [f'Image {i:0>2d}' for i in range(size)]
index = 0
label1 = tk.Label(root, image=images[index])
label1.grid(row=1, column=2)
label2 = tk.Label(root, text=labels[index])
label2.grid(row=2, column=2)
button1 = tk.Button(root, text="<LEFT", width=6, anchor='center', command=lambda num=-1:shift(num))
button1.grid(row=1, column=1)
button2 = tk.Button(root, text="RIGHT>", width=6, anchor='center', command=lambda num=+1:shift(num))
button2.grid(row=1, column=3)
root.mainloop()
You can try this :
from tkinter import Tk,Label,Button
from PIL import ImageTk,Image
import io
import requests
import urllib
root=Tk()
count=0 # To know the current image and label
urls=[url,url1,url2,url3]
labels=["label 1","label 2","label 3","label 4"]
images=[]
for ur in urls:
raw_data = urllib.request.urlopen(ur).read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
images.append(image)
def change(direction): # Function to change image
global count
if direction=="left":
if count<=0:
count=len(urls)-1
else:
count-=1
else:
if count>=len(urls)-1:
count=0
else:
count+=1
name.config(text=labels[count])
image_label.config(image=images[count])
Label(root).grid(row=1,column=1)
image_label=Label(root,image=images[count])
image_label.grid(row=1,column=2)
left_button=Button(root,text="Left",command=lambda : change("left"))
left_button.grid(row=2,column=1)
name=Label(root,text=labels[count])
name.grid(row=2,column=2)
right_button=Button(root,text="Right",command=lambda : change("right"))
right_button.grid(row=2,column=3)
root.mainloop()

is there a way to grid an extra button while running your program in tkinter correctly?

I'm making an mp3 player app and I want the user to be able to add playlists (which will be buttons in a grid system.
Like so.
However in this state when I'm trying to add a playlist button this happens:
The top buttons and the button i just added get squeezed off and the scrollbar is stuck (I can't use it)
I've tried refreshing by self.playlist_frame.update_idletasks() after running create_playlists() but it doesn't seem to change anything
this is my code so you can test it:
import os
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class MyApp:
def __init__(self):
self.root = tk.Tk()
self.width = self.root.winfo_screenwidth()
self.height = self.root.winfo_screenheight()
self.height = self.root.winfo_screenheight() - int(self.height / 13)
self.root.geometry(f'{self.width}x{self.height}')
self.root.title("Mp3")
self.c = '#14141D'
self.playlists_buttons_list = []
self.playlists = {}
self.helping_d = {}
self.main = ttk.Notebook(self.root)
self.playlists_tab = tk.Frame(self.main)
self.playlist_menu_frame = tk.Frame(self.playlists_tab, bg=self.c)
self.playlists_canvas = tk.Canvas(self.playlists_tab, bg=self.c)
self.playlist_frame = tk.Frame(self.playlists_canvas, bg=self.c)
self.playlists_scrollbar = ttk.Scrollbar(self.playlists_tab, orient='vertical',
command=self.playlists_canvas.yview)
self.add_playlist_win = tk.Toplevel(self.root)
self.add_playlists_button = tk.Button(self.playlist_frame)
self.default_img = Image.open('images/default.png').resize((75, 72))
self.default_img = ImageTk.PhotoImage(self.default_img)
self.add_img = Image.open('images/add.png').resize((50, 50))
self.add_img = ImageTk.PhotoImage(self.add_img)
self.widgets()
self.root.mainloop()
def widgets(self):
self.playlists_tab.place(height=self.height, width=self.width, x=0, y=0)
self.main.add(self.playlists_tab, text="Playlists")
self.main.pack(expand=1, fill="both")
self.playlist_frame = tk.Frame(self.playlists_canvas, bg=self.c)
self.playlists_canvas.create_window((0, 0), window=self.playlist_frame, anchor='center')
self.playlists_canvas.config(bg=self.c)
self.playlists_canvas.place(height=int(self.height / 1.428), width=self.width, x=0, y=int(self.height / 9))
self.add_playlists_button = tk.Button(self.playlists_canvas, image=self.add_img, bg=self.c, bd=0,
command=self.add_playlists)
self.add_playlists_button.place(x=1284, y=75)
self.playlists_scrollbar.pack(side='right', fill='y')
self.playlists_canvas.config(yscrollcommand=self.playlists_scrollbar.set)
self.playlists_canvas.bind('<Configure>', lambda e: self.playlists_canvas.configure(
scrollregion=self.playlists_canvas.bbox('all')))
if os.path.getsize('playlistsnames.txt') != 0:
lines = open('playlistsnames.txt', 'r', encoding='utf-8').read().splitlines()
for i in lines:
self.playlists[i] = []
self.create_playlists()
def create_playlists(self):
self.playlists_buttons_list = []
for i in range(len(self.playlists.keys())):
self.playlists_buttons_list.append(tk.Button(self.playlist_frame, bg=self.c,
text=' ' + list(self.playlists.keys())[i].split('!')[0],
fg='white', image=self.default_img, height=280, width=300))
row = 0
column = 0
for i in self.playlists_buttons_list:
if column > 3:
row += 1
column = 0
if column > 7:
row += 1
column = 0
i.grid(row=row, column=column)
column += 1
def get_name(self):
self.name_of_plst = self.plst_entry.get()
self.playlists[self.name_of_plst] = []
self.create_playlists()
with open('playlistsnames.txt', 'a', encoding='utf-8') as names_file:
names_file.write(self.name_of_plst + '!\n')
def add_playlists(self):
self.add_playlist_win = tk.Toplevel(self.root)
self.name_label = tk.Label(self.add_playlist_win, text='Name:', bg=self.c, fg='pink').pack()
self.plst_entry = tk.Entry(self.add_playlist_win)
self.plst_entry.pack()
self.confirm_btn = tk.Button(self.add_playlist_win, text='Confirm', bg=self.c, fg='pink',
command=self.get_name).pack()
self.add_playlist_win.mainloop()
MyApp()
I should also mention that because I store the playlist names in a file called playlistnames.txt when I rerun the program I can see all the playlist buttons plus the one I created before and things work just fine.
So what I want is making the grid update and work while running the app without having to rerun the app of course
My playlistsnames.txt file has this format:
rock!
metal!
chill!
rap!
jazz!
blues!
hard rock!
trap!
Any suggestions would be helpful!
Thanks in advance!

Running into problems with class inheritance an tkinter listBox insert

I am currently trying to make a simple Jukebox/Music Player in Python and ran into some concerns with class inheritance and tkinter's listBox method.
I have to two classes JukeboxGUI and JukeboxContent (the content one is incomplete). The JukeboxContent class inherits the JukeboxGUI:
import os
import pygame
#from PIL import Image
from tkinter.filedialog import askdirectory
from tkinter import *
import eyed3
class JukeboxGUI:
def __init__(self, window):
self.photo = PhotoImage(file = "//Users//nukhbahmajid//Desktop//Jukebox//background2.gif")
self.canvas = Canvas(width = 1000, height = 1000, bg = "black")
self.label = Label(self.canvas, text = "Jukebox")
self.listBox = Listbox(self.canvas)
self.playPauseButton = Button(self.canvas, text = "Play / Pause")
self.nextButton = Button(self.canvas, text = "Next Song")
self.previousButton = Button(self.canvas, text = "Previous Song")
self.stopButton = Button(self.canvas, text = "Stop")
self.labelVar = StringVar()
self.songLabel = Label(self.canvas, textvariable = self.labelVar, width = 20)
def constructButtons(self):
self.canvas.pack()
self.canvas.create_image(0,0, image = self.photo, anchor = NW)
self.label = self.canvas.create_window(325, 40, anchor = NW, window = self.label)
self.listBox = self.canvas.create_window(270, 80, anchor = NW, window = self.listBox)
self.playPauseButton = self.canvas.create_window(110, 120, anchor = NW, window = self.playPauseButton)
self.nextButton = self.canvas.create_window(500, 120, anchor = NW, window = self.nextButton)
self.previousButton = self.canvas.create_window(500, 180, anchor = NW, window = self.previousButton)
self.stopButton = self.canvas.create_window(130, 183, anchor = NW, window = self.stopButton)
self.songLabel = self.canvas.create_window(268, 268, anchor = NW, window = self.songLabel)
class JukeboxContent(JukeboxGUI):
def __init__(self, window):
#JukeboxGUI.__init__(self, window)
super(JukeboxContent, self).__init__(window)
listOfSongs = []
songTitles = []
num_songs = len(songTitles)
self.index = 1
self.listOfSongs = listOfSongs
self.songTitles = songTitles
self.directoryAsk = askdirectory()
self.num_songs = num_songs
self.Error_NoMP3s = "No \".mp3\" files found."
def directoryChooser(self):
self.directoryAsk
os.chdir(self.directoryAsk)
for files in os.listdir(self.directoryAsk):
if files.endswith(".mp3"):
realdir = os.path.realpath(files)
audioTag = eyed3.load(realdir)
self.songTitles.append(audioTag.tag.title)
self.listOfSongs.append(files)
print(files) ## comment out or remove later
print("These are the Song titles:", self.songTitles) #check if the list gets appended
for items in self.songTitles:
self.listBox.insert(END, items) ## the list doesn't get inserted into the listbox
pygame.mixer.init()
pygame.mixer.music.load(self.listOfSongs[0])
self.labelVar.set(self.songTitles[0])
print("The label variable:", self.labelVar) ## the variable isn't set either
print("The label is accessible:", self.songLabel) ## songLabel doesn't get updated
pygame.mixer.music.play() # the song doesn't play
if __name__ == "__main__":
window = Tk()
window.geometry("700x500+450+200")
window.title("Jukebox")
constructGUI = JukeboxGUI(window)
constructGUI.constructButtons()
initiateJukebox = JukeboxContent(window)
initiateJukebox.directoryChooser()
window.mainloop()
When I try to access the attributes of the parent class, like inserting the songs into the list box, there isn't an error here specifically, but the list isn't into the box either
Secondly, when I update the label variable and songLabel, and try to print out later to see if it was implemented, the following gets printed to the terminal:
The label variable: PY_VAR1
The label is accessible: .!canvas2.!label2
The song doesn't play either. What could be the problem? Please help me out! Here's a picture of the interface if it helps:
JukeboxInterface

PhotoImage is not responding to tkinter Scale widget

I have a python script which allows a user to open up an image in a tkinter canvas widget. The program is printing out the size that the new image should be, but only the original image shows up. How do I refresh the canvas with the new size.
Here is the python code:
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
factor = 1.0
width_org = 500
height_org = 500
mGui = Tk()
mGui.geometry("600x600")
mGui.configure(background = 'yellow')
frame = Frame(mGui, width = 400, height = 400)
frame.pack(anchor = 'nw')
frame.configure(background = 'red')
canvasframe = Canvas(frame, width = 400, height = 400, scrollregion = (-500,-500,500,500))
hbar = Scrollbar(frame,orient=HORIZONTAL)
hbar.pack(side=BOTTOM, fill = X)
hbar.configure(command= canvasframe.xview)
vbar = Scrollbar(frame,orient = VERTICAL )
vbar.pack(side=RIGHT, fill = Y)
vbar.configure(command= canvasframe.yview)
canvasframe.configure(xscrollcommand= hbar.set, yscrollcommand= vbar.set)
canvasframe.pack( expand = True, fill = BOTH)
pil_img = Image.open("rose-flower-500x500.jpg")
img = ImageTk.PhotoImage(pil_img)
def openit():
in_path = tkFileDialog.askopenfilename()
try:
pil_img = Image.open(in_path)
except IOError:
pass
width_org, height_org = pil_img.size
try:
img = ImageTk.PhotoImage(pil_img)
except IOError:
pass
canvasframe.create_image(20,20, image = img)
canvasframe.img = img
valueList = [25, 50, 100, 150, 200]
def valuecheck(value):
newval = min(valueList, key=lambda x:abs(x-float(value)))
scalepic.set(newval)
factor = newval/100.0
w = int(width_org*factor)
h = int(height_org*factor)
print (w, h)
pil_img = pil_img.resize((w,h),Image.ANTIALIAS)
img = ImageTk.PhotoImage(pil_img)
canvasframe.create_image(20,20, image =img)
openpic = Button(mGui, text = "Open", command = openit).pack()
scalelabel = Label(mGui, text = "Resize Image").pack()
scalepic = Scale(mGui, from_=min(valueList), to=max(valueList), command=valuecheck, orient = HORIZONTAL)
scalepic.set(100)
scalepic.pack()
mGui.mainloop()
Also, how can I open a new image? I'm thinking of a for loop and some kind of dispose method, but I'm not sure about the syntax.
EDIT
Part of code in classes
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
factor = 1.0
width_org = 500
height_org = 500
class MainApp(Frame):
def createControls(self):
frame = Frame(self, width = 600, height = 500)
frame.configure(background = 'red')
frame.pack(anchor = 'nw')
canvasframe = Canvas(frame, width = 600, height = 500, scrollregion = (-600,-500,600,500))
canvasframe.configure(xscrollcommand= hbar.set, yscrollcommand= vbar.set)
canvasframe.pack(expand = True, fill = BOTH)
hbar = Scrollbar(frame, orient=HORIZONTAL)
hbar.pack(side=BOTTOM, fill=X)
hbar.configure(command= canvasframe.xview)
vbar = Scrollbar(frame, orient=VERTICAL)
vbar.pack(side=RIGHT, fill = Y)
vbar.configure(command= canvasframe.yview)
def __init__(self, parent):
Frame.__init__(self, parent, width = 800, height = 600, background = 'yellow')
self.pack()
self.createControls()
root = Tk()
app = MainApp(parent =root)
app.mainloop()
You forgot to save the reference to the new PhotoImage in canvasframe.img, so it gets garbage collected when valuecheck returns.
Also, rather than creating a new Canvas image with create_image for the rescaled image you should simply update the existing one via itemconfig. To do that, you need to save the item id number returned by create_image. Eg, in openit, do
canvasframe.imgid = canvasframe.create_image(20,20, image = img)
And then in valuecheck, after you create the new PhotoImage do
canvasframe.img = img
canvasframe.itemconfig(canvasframe.imgid, image=img)
You don't have to store img and imgid as attributes of canvasframe, but it's convenient in this case. It would get messy though if you had lots of things on the canvas that you had to track. But for larger Tkinter programs it's a good idea to put everything into one or more classes. It makes things more organized, and easier to access.

Python 2: Replace word in string with icon image.

I am trying to create a weather application. I have a section of code that retrieved weather information from DarkSkyAPI for the next 7 days. The String that is print out looks like Sat clear-day 10. What I am trying to do is display the text I'm a label but replace the clear-sky section of the string for the clear-sky icon I have.
Format I am looking for is Sat {icon} 10
from Tkinter import *
from datetime import timedelta, datetime
from PIL import Image, ImageTk
import requests
import json
## Location of Icons used
icon_lookup = {
'clear-day' : "Icons/WeatherIcons/WeatherIcon.png",
}
class Weather(Frame):
def __init__(self, parent, *args, **kwargs):
Frame.__init__(self, parent, bg = 'black')
self.iconLbl = Label(self, bg="black")
self.iconLbl.grid(row = 0, column = 1, sticky = W)
self.icon = ''
self.get_weather()
def get_weather(self):
try:
## Get Week's Weather Values
todayPlusOne = 'Sat clear-day 10'
## Get Icon
icon_id = 'clear-day'
icon2 = None
if icon_id in icon_lookup:
icon2 = icon_lookup[icon_id]
if icon2 is not None:
if self.icon != icon2:
self.icon = icon2
image = Image.open(icon2)
image = image.resize((100, 100), Image.ANTIALIAS)
image = image.convert('RGB')
photo = ImageTk.PhotoImage(image)
self.iconLbl.config(image=photo)
self.iconLbl.image = photo
else:
self.iconLbl.config(image='')
except Exception as e:
print "Error: %s. Cannot get weather." % e
self.after(900000, self.get_weather)
class FullscreenWindow:
def __init__(self):
self.tk = Tk()
self.tk.configure(background='black')
self.topFrame = Frame(self.tk, background = 'black', height = 240)
self.middleFrame = Frame(self.tk, background = 'black', height = 240)
self.bottomFrame = Frame(self.tk, background = 'black', height = 240)
self.topFrame.pack(side = TOP, fill = BOTH)
self.middleFrame.pack(side = TOP, fill = BOTH)
self.bottomFrame.pack(side = TOP, fill = BOTH)
self.state = False
self.tk.bind('<Return>', self.toggle_fullscreen)
#weather
self.weather = Weather(self.topFrame)
self.weather.pack(side = LEFT, anchor = NW, padx = 25, pady = 25)
def toggle_fullscreen(self, event=None):
self.state = not self.state
self.tk.attributes('-fullscreen', self.state)
return 'break'
if __name__ == '__main__':
w = FullscreenWindow()
w.tk.resizable(width=False, height=False)
w.tk.geometry('720x480')
w.tk.mainloop()
Is this possible to do?
You cannot put an image in the middle of text in a label; you can only put an image on one side (top, bottom, left, right) or centered. To have both text and an image you need to use the compound attribute of the label.
To have an image in the middle of text, there are at least three options:
create a frame with a label for the text, a label for the icon, and another label for more text
use a canvas, and create text and image items on the canvas
use a one-line text widget, which supports embedded images.

Categories