我一直在关注这个Tkinter入门教程。
Link: https://www.youtube.com/watch?v=YXPyB4XeYLA
目前正在浏览图像查看器应用程序教程。
视频中的那个人使用了很多全局变量,我知道这有点不行,所以我做了同样的事情,只是使用类和类方法。 它可以工作,很棒,但是我忍不住觉得它像意大利面条一样不必要,可能有更简单的方法吗?
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()