I've been following along with this Tkinter introduction tutorials.
Link: https://www.youtube.com/watch?v=YXPyB4XeYLA
Currently going through the image viewer app tutorial.
The guy in the video uses a lot of global variables, and I understand that's a bit of a no-no, so I sort of did the same thing but with classes and class methods instead. It works, which is great, but I can't help feel it's unnecessarily spaghetti like and a simpler way might be possible?
Note: I replaced the real directory I used with imagedirectory
from tkinter import *
from PIL import ImageTk, Image
import os
root = Tk()
class mylabel:
def __init__(self):
self.rty = ""
self.imagedict = {}
self.iNum = 0
def removeself(self):
self.rty.grid_forget()
def makeyoself(self, imagenum):
self.rty = Label(root, image=self.imagedict["image" + str(imagenum)])
self.rty.image = self.imagedict["image" + str(imagenum)]
self.rty.grid(row=0, column=1, columnspan=5)
def gettheimages(self):
os.chdir('imagedirectory')
for a, b, c in os.walk('imagedirectory'):
for imgs in range(len(c)):
self.imagedict["image" + str(imgs)] = ImageTk.PhotoImage(Image.open(c[imgs]))
class buttonclass:
def __init__(self, inrelationto):
self.but = ""
self.inrelationto = inrelationto
self.notme = ""
def makeforwarden(self):
self.but = Button(root, text=">>", command = self.forward)
self.but.grid(row=1,column=6)
def makeforwarddis(self):
self.but = Button(root, text=">>", command = self.forward, state=DISABLED)
self.but.grid(row=1,column=6)
def makebackwarden(self):
self.but = Button(root, text="<<", command = self.backward)
self.but.grid(row=1,column=0)
def makebackwarddis(self):
self.but = Button(root, text="<<", command = self.backward, state=DISABLED)
self.but.grid(row=1,column=0)
def removebut(self):
self.but.grid_forget()
def forward(self):
if self.inrelationto.iNum < len(self.inrelationto.imagedict) -1:
self.inrelationto.removeself()
self.inrelationto.makeyoself(self.inrelationto.iNum +1)
if self.inrelationto.iNum == 0:
self.notme.removebut()
self.notme.makebackwarden()
if self.inrelationto.iNum == len(self.inrelationto.imagedict) -2:
self.removebut()
self.makeforwarddis()
self.inrelationto.iNum += 1
def backward(self):
if self.inrelationto.iNum > 0:
self.inrelationto.removeself()
self.inrelationto.makeyoself(self.inrelationto.iNum - 1)
if self.inrelationto.iNum == 1:
self.removebut()
self.makebackwarddis()
if self.inrelationto.iNum == len(self.inrelationto.imagedict) - 1:
self.notme.removebut()
self.notme.makeforwarden()
self.inrelationto.iNum -=1
def setup():
pictureviewer = mylabel()
buttonforward = buttonclass(pictureviewer)
buttonbackward = buttonclass(pictureviewer)
buttonforward.notme = buttonbackward
buttonbackward.notme = buttonforward
pictureviewer.gettheimages()
pictureviewer.makeyoself(0)
buttonforward.makeforwarden()
buttonbackward.makebackwarddis()
if __name__ == '__main__':
setup()
root.mainloop()