此代码将打开一个带有图像的主窗口,然后打开另一个带有相同图像的窗口。有没有办法将图像的大小调整为更小? (转到图像2(第二个窗口))
代码如下:
from tkinter import ttk
from tkinter import *
root = Tk()
root.title('4 Dry Out')
# IMAGE 1 (1st window)
img=PhotoImage(file='4 Dry Out Logo.png')
Label(root,image=img).pack()
# window format
root.geometry("275x75")
root['bg']='blue'
class MainWin:
# main window frame
def __init__(self, master):
mainFrame = Frame(master)
mainFrame.pack()
# main window title / button
self.titleLabel = Label(master, text="4 Dry Out e-Rental", bg="blue", fg="white", font=("Arial Black", 20))
self.titleLabel.pack()
self.Btn = Button(master, text="Water Damage Equipment", command=self.MenuWin, bg="navy", fg="white", font=("Roboto")).pack()
# button: new window
def MenuWin(self):
self.record = Menu()
self.record.win.mainloop()
class Menu:
# new window frame
def __init__(self):
self.win = Toplevel()
self.frameFit = Frame(self.win)
self.frameFit.pack()
self.frameFit['bg']='blue'
# !>>> IMAGE 2 (2nd window)
photo = PhotoImage(file='4 Dry Out Logo.png')
label = Label(self.win,image=photo)
label.image = photo # reference!
label.pack()
# portal title
self.TitleLabel = Label(self.frameFit, text="e-Rental Portal", bg="blue", fg="white", font=("Arial Black",15)).pack()
# start / end
winStart = MainWin(root)
root.mainloop()
我看到Bryan Oakley已经发布了一个关于你问题的答案,但我将用我自己的补充,它还修复了我在你的代码中注意到的几个其他问题(一些与this有关),并展示了如何使用Bryan在comment中提到的
subsample()
方法调整图像大小而不使用PIL在你的相关问题下,该问题已作为副本关闭通过使用Python控制台中的Python内置帮助系统,您可以找到一些关于它的文档,
copy()
,zoom()
,以及Photoimage
类的其他方法:即当然,它也在source code中
以下是问题代码中的代码以及修复程序:
我没有您的
4 Dry Out Logo.png
徽标图像,但以下是在我的系统上使用替代图像运行时单击按钮后的情况错误
NameError: name 'photo' is not defined
来自此行:正如错误所说,您从未定义过
photo
。我猜您只是从某个地方复制了这段代码,而不了解代码在做什么。在本例中,您复制的代码试图保存对先前创建的图像的引用。您重命名了图像或更改了此语句中的名称,从而导致了错误。它与创建第二个窗口无关代码应该类似于以下内容,不过我添加了一些注释以显示需要使用相同名称的三个位置:
您的问题是,您在最后一行中使用了
photo
,而您本应使用img
代码的要点是,在创建图像后,它通过将图像指定给
tktext_label.image
来保存对图像的引用。保存引用的原因在问题Why does Tkinter image not show up if created in a function?的this answer中解释A simple search of this site将回答这个问题
首先,您引用的是未定义为变量的
photo
(除非它位于另一个文件中,并且您尚未导入它)。这就是错误的来源要调整图像大小,您需要PIL包-
pip install pillow
在此之后,您可以导入它并以以下方式使用它:
相关问题 更多 >
编程相关推荐