[英]How to pass arguments when instantiating a class to a function in Python?
I have tried to portray and document each class only what is necessary, hope you can help me please, I am trying to instantiate the class Show_image
which requires two parameters, two indexes of a list of images, if you could guide me if what I am trying to do is possible I would appreciate it.我已尝试仅描绘和记录每个 class 所需的内容,希望您能帮助我,我正在尝试实例化class
Show_image
,它需要两个参数,图像列表的两个索引,如果您能指导我的话我想做的是可能的,我将不胜感激。 Thanks.谢谢。
This class resizes the image这 class 调整图像大小
from tkinter importante *
from PIL import Image, ImageTk
class Array(Frame):
def __init__(self, master, path, *args):
Frame.__init__(self, master, *args) self.image = Image.open(path)
self.img_copy = self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = Label(self, image=self.background_image)
self.background.pack(fill='both', expand=True)
self.background.bind('<Configure>', self._resize_image)
def _resize_image(self, event):
self.image = self.img_copy .resize ((self.master .winfo_width(), self.master .winfo_height()))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image=self.background_image)
Base class control基地 class 控制
class Interface(Frame):
def __init__(self, master, *args):
Frame.__init__(self, master, *args)
self.path_lst = ['11.png','22.png','33.png','44.png'] # change/add paths
self._frame_1 = None
self._open_1 = False
self.button1 = Button(self, text='pack 1',
command= lambda:self.windows(Show_image))
self.button1 .pack()
def windows(self, var_1):
if not self._open_1:
self.top1 = Toplevel(self.master)
self.top1 .geometry('200x200')
container = var_1(self.top1)
if self._frame_1 is not None:
self._frame_1 .destroy()
self._frame_1 = container
self._frame_1 .pack()
self._open_1 = True
self.top1.protocol ('WM_DELETE_WINDOW', lambda: self.closed(1))
def closed(self, number):
if number == 1:
self.top1. destroy()
self._open_1 = False
This class should draw two instances, two images, but I don't know how to pass <index_1>
and <index_2>
arguments in bound <lambda>
function.这个 class 应该绘制两个实例,两个图像,但我不知道如何在绑定
<lambda>
function 中传递<index_1>
和<index_2>
arguments。
class Show_image(Frame):
def __init__(self, index_1, index_2, *args, **kwargs):
Frame.__init__(self, *args, **kwargs)
self.img = Array(self, self.master.path_lst[index_1])
self.img .grid(column=0, row=0)
self.img2 = Array(self, self.master.path_lst[index_2])
self.img2 .grid(column=0, row=1)
root = Tk()
frm = Interface(root)
frm .pack()
root.mainloop()
Also, if you could tell me if the initialization path of the images is correct.另外,如果你能告诉我图像的初始化路径是否正确。 Thanks.
谢谢。
If I understant you will have to use nested lambdas
如果我明白你将不得不使用嵌套的
lambdas
command=lambda:self.windows(lambda:Show_image(index1, index2))
but I see that windows
runs function with argument top
so it will need it also in lambda
但我看到
windows
以参数top
运行 function 所以它在lambda
中也需要它
command=lambda:self.windows( lambda top:Show_image(index1, index2, top))
EDIT:编辑:
Full working code with other changes.具有其他更改的完整工作代码。
I send master
as first value and path_lst
as last value and I don't need to use self.master.pack_lst
我将
master
作为第一个值发送,将path_lst
作为最后一个值发送,我不需要使用self.master.pack_lst
I changed some pack()
, grid()
and I added grid_rowconfigure()
so it correctly resize images when window change size.我更改了一些
pack()
、 grid()
并添加了grid_rowconfigure()
以便在 window 更改大小时正确调整图像大小。
I used os.listdir()
to create path_lst
.我使用
os.listdir()
创建path_lst
。 It uses sys.argv
to get folder
from command line ( python script.py path_to_images
) or it uses os.getcwd()
to get Current Working Directory
as folder
它使用
sys.argv
从命令行 ( python script.py path_to_images
) 获取folder
,或者使用os.getcwd()
获取Current Working Directory
作为folder
I changed name to ShowImage
as suggest PEP8
- CamelCaseNames
for classes.我按照建议将名称更改为
ShowImage
PEP8
- CamelCaseNames
for classes。
I'm not sure if it suggests to use noun
for classes (like noun ImageViewer
instead of verb ShowImage
) and verb
for functions (like verb show_window
instead of noun windows
) but I skip it.我不确定它是否建议对类使用
noun
(例如名词ImageViewer
而不是动词ShowImage
)和对函数使用verb
(例如动词show_window
而不是名词windows
),但我跳过了它。 Maybe it is suggestion in book 'Clean Code' by Robert C. Martin (also known as Uncle Bob )也许这是罗伯特 C 在“清洁代码”一书中的建议。马丁(也称为鲍勃叔叔)
PEP 8 -- Style Guide for Python Code PEP 8 -- Python 代码风格指南
import os # os.path.join(), os.listdir()
import sys # sys.argv
#from tkinter import * # PEP8: `import *` is not preferred
import tkinter as tk
from PIL import Image, ImageTk
# --- constants --- # PEP8: `UPPER_CASE_NAMES
#FOLDER = '/home/furas/test'
# --- classes --- # PEP8: `CamelCaseNames`
class Array(tk.Frame):
def __init__(self, master, path, *args):
super().__init__(master, *args) # in Python 3 you can use `super()` without `self`
self.image = Image.open(path)
self.img_copy = self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = tk.Label(self, image=self.background_image)
self.background.pack(fill='both', expand=True)
self.background.bind('<Configure>', self._resize_image)
def _resize_image(self, event):
self.image = self.img_copy.resize((self.master.winfo_width(), self.master.winfo_height()//2))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image=self.background_image)
class Interface(tk.Frame):
def __init__(self, master, folder, *args):
super().__init__(master, *args)
self.folder = folder
#self.path_lst = ['11.png','22.png','33.png','44.png'] # change/add paths
self.path_lst = [os.path.join(self.folder, name) for name in os.listdir(self.folder) if name.lower().endswith(('.png', '.jpg', '.gif'))] # change/add paths
self._frame_1 = None
self._open_1 = False
index_1 = 0
index_2 = 1
self.button1 = tk.Button(self, text='pack 1',
command=lambda:self.windows(lambda top:ShowImage(top, index_1, index_2, self.path_lst)))
self.button1.pack()
def windows(self, var_1):
if not self._open_1:
self.top1 = tk.Toplevel(self.master)
self.top1.geometry('200x200')
container = var_1(self.top1)
if self._frame_1 is not None:
self._frame_1.destroy()
self._frame_1 = container
self._frame_1.pack(fill='both', expand=True)
self._open_1 = True
self.top1.protocol('WM_DELETE_WINDOW', lambda: self.closed(1))
def closed(self, number):
if number == 1:
self.top1.destroy()
self._open_1 = False
class ShowImage(tk.Frame):
def __init__(self, master, index_1, index_2, path_lst, *args, **kwargs):
super().__init__(master, *args, **kwargs)
if len(path_lst) > index_1:
self.img = Array(self, path_lst[index_1])
self.img.grid(column=0, row=0, sticky='news')
if len(path_lst) > index_2:
self.img2 = Array(self, path_lst[index_2])
self.img2.grid(column=0, row=1, sticky='news')
# column 0 will use full width
self.grid_columnconfigure(0, weight=1)
# row 0 will use 1/2 height AND row 1 will use 1/2 height
self.grid_rowconfigure(0, weight=1)
self.grid_rowconfigure(1, weight=1)
# --- functions --- # PEP8: `lower_case_names`
# empty
# --- main ---
if len(sys.argv) > 1:
folder = sys.argv[1]
else:
folder = os.getcwd()
#folder = FOLDER
root = tk.Tk()
frm = Interface(root, folder)
frm.pack()
root.mainloop()
BTW:顺便提一句:
Because window has to display two images so I divide height by 2 ( self.master.winfo_height()//2
) in Array
to fit both rows/images in window.因为 window 必须显示两个图像,所以我将数组中的高度除以 2 (
self.master.winfo_height()//2
) 以适应Array
中的两个行/图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.