python - 为什么当我尝试在另一个文件中调用函数时解释器在 tkinter 中输出 namerror
问题描述
我已经Win.py
调试了文件,它运行良好。但是,根据@Matiiss,我会写这样的函数
def func():
lbl = ImageLabel(root)
lbl.pack()
lbl.load('D:/Personal/Game/Win.gif')
在主文件中,即 . start2.py
,但是当我在命令中插入函数时,python 输出类似NameError: name 'root' is not defined
. 我不确定是否需要更改root
为其他内容,因为我确实没有root
在任何一个文件中看到任何内容。以下是该Win.py
文件的代码。
import tkinter as tk
from PIL import Image, ImageTk
from itertools import count, cycle
class ImageLabel(tk.Label):
def load(self, im):
if isinstance(im, str):
im = Image.open(im)
frames = []
try:
for i in count(1):
frames.append(ImageTk.PhotoImage(im.copy()))
im.seek(i)
except EOFError:
pass
self.frames = cycle(frames)
try:
self.delay = im.info['duration']
except:
self.delay = 100
if len(frames) == 1:
self.config(image=next(self.frames))
else:
self.next_frame()
def unload(self):
self.config(image=None)
self.frames = None
def next_frame(self):
if self.frames:
self.config(image=next(self.frames))
self.after(self.delay, self.next_frame)
我不知道在哪里root
,但我不知道要在里面添加哪个参数lbl=ImageLabel()
。
的代码start2.py
,缩进正确。
import tkinter as tk
import pygame
from playsound import playsound
from Win import ImageLabel
display_width = 1000
display_height = 500
# Set up the display size
white = (255, 255, 255) # White
red = (255, 0, 0) # Red button background
picture = 'D:/Personal/Game UI.jpg' # The location of the picture
pygame.init() # Initialize class+
class Button(object): # Button class
def __init__(self, text, color, x=None, y=None, **kwargs):
self.surface = font.render(text, True, color)
self.WIDTH = self.surface.get_width()
self.HEIGHT = self.surface.get_height()
if 'centered_x' in kwargs and kwargs['centered_x']: # Show the place that a button will show up (x-axis)
self.x = display_width // 2 - self.WIDTH // 2
else:
self.x = x
if 'centered_y' in kwargs and kwargs['centered_y']: # Show the place that a button will show up (y-axis)
self.y = display_height // 2 - self.HEIGHT // 2
else:
self.y = y
def display(self):
screen.blit(self.surface, (self.x, self.y)) # Can't assign a value to a function
def check_click(self, position): # Track mouse behavior to show highlights
x_match = position[0] > self.x and position[0] < self.x + self.WIDTH
y_match = position[1] > self.y and position[1] < self.y + self.HEIGHT
if x_match and y_match:
return True
else:
return False
def start_screen(): # This function is used to load background and music
screen.blit(bg, (0, 0))
game_title = font.render("Start", True, white)
screen.blit(game_title, (display_width // 2 - game_title.get_width() // 2, 150))
play_button = Button("Play", red, None, 350, centered_x=True) # Start the game
exit_button = Button("Exit", white, None, 400, centered_x=True) # Exit the game
play_button.display()
exit_button.display()
pygame.display.update()
while True: # A conditional reading from while loop
if play_button.check_click(pygame.mouse.get_pos()):
play_button = Button('Play', red, None, 350, centered_x=True)
else:
play_button = Button('Play', white, None, 350, centered_x=True)
if exit_button.check_click(pygame.mouse.get_pos()):
exit_button = Button("Exit", red, None, 400, centered_x=True)
else:
exit_button = Button("Exit", red, None, 400, centered_x=True)
play_button.display()
exit_button.display()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
raise SystemExit
if pygame.mouse.get_pressed()[0]:
if play_button.check_click(pygame.mouse.get_pos()):
break
if exit_button.check_click(pygame.mouse.get_pos()):
break
screen = pygame.display.set_mode((display_width, display_height)) # The use of the functions above
bg = pygame.image.load(picture)
font_addr = pygame.font.get_default_font()
font = pygame.font.Font(font_addr, 36)
start_screen()
LARGE_FONT = ("Verdana", 12) # Font
# TODO: sound is defined here
def fail1():
playsound("D:/Personal/Game/wha-wha.mp3", block=False)
def fail2():
playsound("D:/Personal/Game/Nope-Sound-Effect.wav", block=False) # TODO: bug here, use wav format
def fail3():
playsound("D:/Personal/Game/friday-damn.mp3", block=False)
def fail4():
playsound("D:/Personal/Game/export_4.mp3", block=False)
def fail5():
playsound("D:/Personal/Game/Aww.mp3", block=False)
def fail6():
playsound("D:/Personal/Game/Laughing.mp3", block=False)
def fail7():
playsound("D:/Personal/Game/Incorrect.mp3", block=False)
def give_up():
playsound("D:/Personal/Game/Fail.mp3", block=False)
def try_again():
playsound("D:/Personal/Game/Here-we-go.mp3", block=False)
def success1():
playsound("D:/Personal/Game/Yah.mp3", block=False)
def gif():
top = tk.Toplevel(app)
lbl = ImageLabel(top)
lbl.pack()
lbl.load('D:/Personal/Game/Win.gif')
class SeaofBTCapp(tk.Tk): # Define a class for the tk windows
def __init__(self, *args, **kwargs): # Base properties of tk windows
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
'''https://stackoverflow.com/questions/64470478/keyerror-class-main-page2-in-python-tkinter For range means
that the buttons will be loaded for multiple times, whenever a new option is added, for range needs to be
defined. '''
for F in (
StartPage, MCQ, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Failure, Success,
Credits): # TODO: add the class number into the for loop here
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame): # Start page
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="This will test your chemistry ability. Ready to start?", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button = tk.Button(self, text="Enter",
command=lambda: [controller.show_frame(MCQ), try_again()]) # This will show the next window
button.pack()
button2 = tk.Button(self, text="Cancel",
command=lambda: controller.destroy()) # This will close the window
button2.pack()
class MCQ(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!! Question 1: What is proton number equal to?", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Atomic mass",
command=lambda: [self.correspondingBehavior("Sorry, you died. Better luck next time!"),
controller.show_frame(Failure), fail1()])
button1.pack()
button2 = tk.Button(self, text="Number of moles",
command=lambda: [self.correspondingBehavior("Sorry, you died. Better luck next time!"),
controller.show_frame(Failure), fail1()])
button2.pack()
button3 = tk.Button(self, text="Atomic number",
command=lambda: controller.show_frame(Q2))
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q2(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!! Question 2: Which of the two statements describes the word "
"endothermic?", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Give out heat", command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah..."),
controller.show_frame(Failure), fail2()])
button1.pack()
button2 = tk.Button(self, text="Take in heat", command=lambda: controller.show_frame(Q3))
button2.pack()
button3 = tk.Button(self, text="Give up",
command=lambda: self.correspondingBehavior("Don't give up!"))
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q3(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!! Question :3 he symbol Ag stands for which element?", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Gold",
command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah... EPIC FAIL!!! Gold is Au!"),
controller.show_frame(Failure), fail2()])
button1.pack()
button2 = tk.Button(self, text="Silver", command=lambda: controller.show_frame(Q4))
button2.pack()
button3 = tk.Button(self, text="Hydrogen",
command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah... EPIC FAIL!!! Hydrogen is H!"),
controller.show_frame(Failure), fail2()])
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q4(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!! Question 3: Organic chemistry is the study of the compounds that "
"make up living organisms. All organic molecules contain:", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Carbon only",
command=lambda: [self.correspondingBehavior("WHH! Check your book.."),
controller.show_frame(Failure), fail3()])
button1.pack()
button2 = tk.Button(self, text="Carbon and nitrogen",
command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah... You died!"),
controller.show_frame(Failure), fail3()])
button2.pack()
button3 = tk.Button(self, text="Carbon and hydrogen",
command=lambda: controller.show_frame(Q5))
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q5(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!!A molecule with the formula C3H8 is a(n)", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="hexane",
command=lambda: [self.correspondingBehavior("Nope, it's C6H14"),
controller.show_frame(Failure), fail4()])
button1.pack()
button2 = tk.Button(self, text="propane", command=lambda: controller.show_frame(Q6))
button2.pack()
button3 = tk.Button(self, text="butane",
command=lambda: [self.correspondingBehavior("Nope, it's C4H10"),
controller.show_frame(Failure), fail4()])
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q6(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!!A substance that speeds up the rate of a chemical reaction without "
"undergoing any change itself "
"is known as a _______", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="catalyst",
command=lambda: controller.show_frame(Q7))
button1.pack()
button2 = tk.Button(self, text="cation", command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah... What a "
"pity! But cation is a "
"positive charge."),
controller.show_frame(Failure), fail4()])
button2.pack()
button3 = tk.Button(self, text="counter ion",
command=lambda: [self.correspondingBehavior("Nope, it's the ion that accompanies an ionic "
"species in order to maintain electric "
"neutrality."), controller.show_frame(Failure),
fail4()])
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q7(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!! All of the following are amino acids except:",
font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Tryptophan",
command=lambda: [self.correspondingBehavior("Nope, adenine is a nucleic acid, not an "
"amino acid."), controller.show_frame(Failure),
fail6()])
button1.pack()
button2 = tk.Button(self, text="Tyrosine",
command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah... Adenine is a nucleic acid, "
"not an amino acid."),
controller.show_frame(Failure), fail6()])
button2.pack()
button3 = tk.Button(self, text="Adenine",
command=lambda: controller.show_frame(Q8))
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q8(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!!A mole contains Avogadro's number of items. What is Avogadro's number?",
font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="6023",
command=lambda: [self.correspondingBehavior("Wrong...Check your chemistry book"),
controller.show_frame(Failure), fail5()])
button1.pack()
button2 = tk.Button(self, text="C. 6.02 x 10^-23",
command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah... What a "
"pity! But the value is larger than that..."),
controller.show_frame(Failure), fail5()])
button2.pack()
button3 = tk.Button(self, text="6.023 x 10^23",
command=lambda: controller.show_frame(Q9))
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q9(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!!The person given credit for developing the first modern periodic "
"table is",
font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Democritus",
command=lambda: [self.correspondingBehavior("Wrong...He was famous for the formulation of "
"an atomic theory of the universe"),
controller.show_frame(Failure), fail7()])
button1.pack()
button2 = tk.Button(self, text="Mendeleev",
command=lambda: controller.show_frame(Q10))
button2.pack()
button3 = tk.Button(self, text="Thomson",
command=lambda: [self.correspondingBehavior("Wah-ah-ah-ah... What a "
"pity! He is the one who did a detailed study "
"of cathode rays and proved the existence of "
"the electron in atoms"),
controller.show_frame(Failure), fail7()])
button3.pack()
button4 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button4.pack()
def correspondingBehavior(self, choice):
print(choice)
class Q10(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!! Does group or period in the periodic table represent outer shell "
"electrons?",
font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Period",
command=lambda: [self.correspondingBehavior("Wrong...You can draw it out and see"),
controller.show_frame(Failure), fail7()])
button1.pack()
button2 = tk.Button(self, text="Group",
command=lambda: (controller.show_frame(Success))) # TODO: find a way
button2.pack()
button3 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button3.pack()
def correspondingBehavior(self, choice):
print(choice)
class Success(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Yay! You have passed my chemistry challenge! Would you like to continue?",
font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Continue", command=[gif(), success1()])
button1.pack()
button2 = tk.Button(self, text="Quit", command=lambda: controller.destroy())
button2.pack()
def correspondingBehavior(self, choice): # Comment
print(choice)
class Failure(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Sorry about that, but you failed. Would you like to try again?",
font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Yes", command=lambda: [controller.show_frame(MCQ), try_again()])
button1.pack()
button2 = tk.Button(self, text="No", command=lambda: controller.show_frame(Credits))
button2.pack()
def correspondingBehavior(self, choice):
print(choice)
app = SeaofBTCapp()
app.mainloop()
'''
Now the codes are in a mess and I am going to write the comments after debugging.
解决方案
由于没有关于 的信息start2.py
,以下是您可以start2.py
根据您发布的代码输入的示例:
import tkinter as tk
from Win import ImageLabel
def func():
lbl = ImageLabel(root)
lbl.pack()
lbl.load("D:/Personal/Game/Win.gif")
root = tk.Tk() # the root window for the ImageLabel
func()
root.mainloop()
推荐阅读
- latex - LaTex:includepdf 的问题。包含后没有签名
- python - 如何在 Python (Plotly Express) 中创建具有百分比值的条形图?
- apache-spark - 相同的查询导致 Hive 与 Spark 中的不同输出
- reactjs - 如何在异步函数react Hook中使用useState
- wordpress - 如何使用 REST API 在 WooCommerce / Elementor 中创建预订平台?
- python - 如何将列表中的元素与列表列表中的元素匹配
- django - NoReverseMatch at /accounts/login/ in django()
- xamarin - 我可以使用 Instagram 在我的 Xamarin Forms 应用程序中对用户进行身份验证吗?
- jhipster - 使用 Jhipster 应用程序获取用户创建异常
- hazelcast - Vertx 集群事件总线未删除 Kubernetes 滚动部署中的旧节点