此代碼將打開一個帶有影像的主視窗,然后是另一個帶有相同影像的視窗。有沒有辦法將影像調整為更小?(轉到 # !>>> 影像 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()
uj5u.com熱心網友回復:
錯誤NameError: name 'photo' is not defined來自這一行:
tktext_label.image = photo
就像錯誤所說的那樣,您從未定義photo. 我猜你只是從某個地方復制了這段代碼,而沒有理解代碼在做什么。在這種情況下,您復制的代碼試圖保存對先前創建的影像的參考。您要么重命名了影像,要么更改了此陳述句中的名稱,從而導致了錯誤。它與創建第二個視窗無關。
代碼應該類似于以下內容,盡管我添加了一些注釋以顯示需要使用相同名稱的三個地方:
img=PhotoImage(file='4 Dry Out Logo.png')
###
Label(self.win,image=img).pack()
###
tktext_label.image = img
###
您的問題是您photo在本應使用img.
代碼的重點是,在創建影像后,它通過將其分配給 來保存對影像的參考tktext_label.image。保存參考的原因在
uj5u.com熱心網友回復:
首先,您參考photo的不是變數(除非它在另一個檔案中并且您沒有匯入它)。這就是錯誤的來源。
要調整影像大小,您將需要 PIL 包 - pip install pillow
在此之后,您可以匯入它并以這種方式使用它:
from PIL import Image, ImageTk
img = (Image.open("4 Dry Out Logo.png"))
image_resize = img.resize((w, h), Image.ANTIALIAS)
final_image = imageTK.PhotoImage(image_resize)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/317168.html
下一篇:如何在Flask中旋轉影像?
