【发布时间】:2021-11-29 06:21:57
【问题描述】:
此代码将打开一个带有图像的主窗口,然后打开另一个带有相同图像的窗口。但是,下面的代码会导致这个错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/ambbrash/fp.py", line 31, in MenuWin
self.record = Menu()
File "/home/ambbrash/fp.py", line 44, in __init__
tktext_label.image = photo
NameError: name 'photo' is not defined
关于如何解决这个问题的任何建议? 另外,有没有办法调整图片大小?
代码如下:
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()
# IMAGE 2 (2nd window)
# img = PhotoImage(file = '4 Dry Out Logo.png')
# Label(win, image=img).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
img=PhotoImage(file='4 Dry Out Logo.png')
Label(self.win,image=img).pack()
tktext_label.image = photo
# 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()
【问题讨论】:
-
请提供minimal reproducible example和完整的错误回溯(从“Traceback”一词开始)(您可以edit您的问题)
-
一个大问题是你正在导入一个“菜单”类,但也定义了一个。正是出于这个原因,PEP8 建议您不要使用通配符导入。请改用
import tkinter as tk。另一个问题是您有两次mainloop()呼叫。这应该在整个程序中只发生一次。 -
该错误意味着您在某些时候提供了
self而不是self.framefit作为主人。 -
@Novel 我应该删除 def MenuWin 中的 mainloop() 吗?此外,如果我更改为将 tkinter 作为 tk 导入,则程序不会运行。我该如何进行格式化?