【问题标题】:Tkinter image viewer app - Classes vs Global VariablesTkinter 图像查看器应用程序 - 类与全局变量
【发布时间】:2020-05-18 02:18:18
【问题描述】:

我一直在关注这个 Tkinter 介绍教程。

链接:https://www.youtube.com/watch?v=YXPyB4XeYLA

目前正在学习图像查看器应用教程。

视频中的那个人使用了很多全局变量,我知道这有点禁忌,所以我做了同样的事情,但使用了类和类方法。 它有效,这很棒,但我不禁觉得它像意大利面条一样不必要,并且可能有更简单的方法?

注意:我用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()

【问题讨论】:

    标签: python python-3.x tkinter tk


    【解决方案1】:

    我会说全局变量对于小程序来说是可以的。另外,您的 OOP 代码看起来有点意大利面条的原因是因为您是这样编写的。思考如何最好地使用对象构建应用程序是一项后天技能,您必须检查一堆示例才能掌握它。因此,这里有一个如何构建应用程序的示例:

    from tkinter import *
    from PIL import ImageTk, Image
    import os
    
    class viewer(Frame):
        def __init__(self, master):
            super().__init__()
    
            # Create image list
            self.image_list = []
            cwd = r'C:\Users\qwerty\Documents\Python\images'
            for path, dirs, files in os.walk(cwd):
                for file in files:
                    full_name = os.path.join(path, file)
                    self.image_list.append(ImageTk.PhotoImage(Image.open(full_name)))
    
            # Create GUI
            self.image_index = 0
            self.picture = Label(self, image=self.image_list[self.image_index])
            self.picture.pack()
            button_frame = Frame(self)
            button_frame.pack(expand=True, fill='x')
            self.buttonforward = Button(button_frame, text='>>', command=self.forward)
            self.buttonforward.pack(side='right')
            self.buttonbackward = Button(button_frame, text='<<', command=self.backward)
            self.buttonbackward.pack(side='left')
            self.buttonbackward.config(state='disabled')
    
        def forward(self):
            self.image_index = self.image_index + 1
            if self.image_index == len(self.image_list) - 1:
                self.buttonforward.config(state='disabled')
            self.buttonbackward.config(state='normal')
            self.picture.config(image=self.image_list[self.image_index])
    
        def backward(self): 
            self.image_index = self.image_index - 1
            if self.image_index == 0:
                self.buttonbackward.config(state='disabled')
            self.buttonforward.config(state='normal')
            self.picture.config(image=self.image_list[self.image_index])
    
    if __name__ == '__main__':
        root = Tk()
        z = viewer(root)
        z.pack()
        root.mainloop()
    

    这里是学习的好地方:Best way to structure a tkinter application?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 2015-05-26
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2021-10-13
      • 2011-12-13
      • 1970-01-01
      相关资源
      最近更新 更多