在python / pyqt中每次单击循环增量

时间:2014-12-30 19:35:57

标签: python pyqt

我使用python / pyqt创建了简单的图像查看器。我想更改标签中的图像,因为每个“下一个”或“上一个”按钮都会被点击。我使用以下代码来增加: -

if self.sender().objectName() == "next_button":
            for i, name in list(enumerate(array)):
                myPixmap = QtGui.QPixmap(os.path.join("data", "images", name))
                myScaledPixmap = myPixmap.scaled(self.ui.label.size(), QtCore.Qt.KeepAspectRatio)
                #self.ui.label.setScaledContents(True) # For streching the image up to entire lable...
                self.ui.label.setPixmap(myScaledPixmap)
                print i, name
                break

正如预期的那样,图像首先在列表中被触发。任何导致解决问题的方法都是适当的。

1 个答案:

答案 0 :(得分:1)

首先将其转换为迭代器,然后在每次想要下一件事时调用next(my_iterator)

from itertools import cycle
class Whatever:
    fnames = cycle(["im1.gif","im2.gif","im3.gif"])
    def on_button(self,*args,**kwargs):
        if self.sender().objectName() == "next_button":
           next_path = os.path.join("data", "images", next(self.fname))
           myPixMap = QtGui.QPixmap(next_path)
           ...

然后,这将循环浏览那些文件名,每次点击都会有一个新文件名

例如

from Tkinter import *
from itertools import cycle
#from tkinter import ttk
def on_button():
    label.set(next(names))

root = Tk()
root.title("Iterator")

mainframe = Frame(root)
mainframe.grid()
names = cycle(["im1.gif","im2.gif","im3.gif"])
label = StringVar()
label.set("Click Next To Cycle Through")
Label(mainframe, textvariable=label).grid(column=2, row=2, sticky=(W, E))
Button(mainframe, text="next", command=on_button).grid(column=3, row=3, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)


root.mainloop()