Python 如何调整从Tkinter中的optionmenu显示的图像的大小?

Python 如何调整从Tkinter中的optionmenu显示的图像的大小?,python,tkinter,Python,Tkinter,如标题所述,如何动态调整图片大小? 功能:单击“其他”按钮时,将显示一个打开的菜单。optionmenu显示我在代码中指定的文件夹中的图像。所有的图像都有不同的大小。如何在调整长宽比的同时保持长宽比 ... def otherdrops(): other_opt = wother other_opt.config(width=50, font=('Helvetica', 12)) other_opt.pack() def other_images(wother):

如标题所述,如何动态调整图片大小? 功能:单击“其他”按钮时,将显示一个打开的菜单。optionmenu显示我在代码中指定的文件夹中的图像。所有的图像都有不同的大小。如何在调整长宽比的同时保持长宽比

...
def otherdrops():
    other_opt = wother
    other_opt.config(width=50, font=('Helvetica', 12))
    other_opt.pack()   
def other_images(wother):
    print(wother)  # selected option
    other_label.config(image=other[wother])
other_label = tk.Label(otherframe)
other_label.pack(side = 'bottom', pady=padylength)
other = {}
for other_name in tradinglists.tradingotherimages:
    other[other_name] = ImageTk.PhotoImage(Image.open("/Images/{}.png".format(other_name)))
othervariable = tk.StringVar(tab2)
othervariable.set(tradinglists.tradingotherimages[0])
wother = tk.OptionMenu(otherframe, othervariable, *tradinglists.tradingotherimages, command=other_images)
def refreshother():
    otherframe.pack_forget() if otherframe.winfo_manager() else otherframe.pack(anchor='center')
other_k = tk.Button(wavebtnframe, bg = "red", text="Other", width = artbtn_width, height = btnsize_height, command=lambda:[otherdrops(), refreshother()])
other_k.pack(side = 'left', padx=wavebtnspadx, pady=padylength)
V2:


您可以使用
image\u name调整图像大小。调整大小((宽度、高度))
我会做一个这样的方法:

def importImageWithResize(filename):
    img = Image.open(filename)
    width, height = img.size
    ratio = width / height
    new_height = preset_height
    new_width = int(new_height * ratio)
    return img.resize((new_width, new_height ))
然后将导入行更改为匹配:

other[other_name] = ImageTk.PhotoImage(importImageWithResize("/Images/{}.png".format(other_name)))
我假设你有一个设定的高度,你希望他们都匹配,但你可以改变它有一个预设的宽度或任何你想要的。如果你对你想要的尺寸有具体的规定并且需要帮助,请随意询问例子


如果您有更多问题等,请告知我们。

比率=旧高度/旧宽度
以及以后的
新宽度=某些值
新高度=新宽度*比率
。并使用模块
PIL
/
枕头
调整其大小。请参阅。嘿,谢谢您的帮助!我试了你的建议,结果出了一个错误。ValueError:未知的重采样筛选器(350)。使用Image.NEAREST(0)、Image.LANCZOS(1)、Image.BILINEAR(2)、Image.BICUBIC(3)、Image.BOX(4)或Image.HAMMING(5)我输入的预设高度为20。对不起,我键入了错误的大小线;我将编辑答案。resize(width,height)应该是带有双括号的img.resize((width,height)),所以现在它不会给我任何错误,我可以运行应用程序,但我看不到高度或大小的任何变化。我用版本2更新了我原来的帖子。你能检查一下我有没有做错什么吗?
img.resize((宽度,高度))
应该是
img.resize((新宽度,新高度))
。谢谢大家
new_height*ratio
给出了一个浮点结果,因此将其更改为
int(new_height*ratio)
。现在效果很好!
other[other_name] = ImageTk.PhotoImage(importImageWithResize("/Images/{}.png".format(other_name)))