所以我对 python 很陌生,所以这可能是一个简单的问题,我只是不明白这里发生了什么。但本质上我有一个下拉菜单,允许您选择一个角色,然后显示相应的角色图像。它第一次工作正常,但问题是我试图在选择新图像后清除图像,并且不断收到错误消息“UnboundLocalError:无法访问与它不相关的局部变量‘imageAppear’”一个值”
这让我感到困惑,因为我将“imageAppear”设置为全局变量,所以我不明白为什么它认为它是局部变量。
目前此代码只会在旧图像下方显示新图像。
我已附上下面的代码,任何帮助将不胜感激
### MAIN WINDOW ###
# Using tkinter version 8.6
# Visit https://docs.python.org/3/library/tkinter.html for documentation
# Using pack as the LayoutManager,
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import pathlib
from pathlib import Path
def main():
root = tk.Tk()
root.geometry('1280x760')
root.title("Slippi Stats")
title = Label(root, text = "Slippi Stats", font = ('Helvetica 20 bold')).pack(pady = 20)
# Create a File Explorer label
global label_file_explorer
label_file_explorer = Label(root,
text = "File Explorer using Tkinter",
width = 100, height = 4)
# Select Character
characters = ["Mario", "Bowser", "Peach", "Yoshi", "Donkey Kong",
"Captain Falcon", "Fox", "Ness", "Ice Climbers",
"Kirby", "Samus", "Zelda", "Link", "Pikachu",
"Jigglypuff", "Dr. Mario", "Luigi", "Ganondorf",
"Falco", "Young Link", "Pichu", "Mewtwo",
"Mr. Game & Watch", "Marth", "Roy"]
global selectedCharacter
global label1
label1 = Label(root, image = "")
global imageAppear
imageAppear = True
selectedCharacter = tk.StringVar(master=root) #Always pass the 'master' keyword argument
selectedCharacter.set("Mario")
selectedCharacter.trace_add('write', characterImage)
characterLabel = tk.Label(root, text="Select a character to train against")
characterLabel.pack(pady=10)
dropdown = tk.OptionMenu(root, selectedCharacter, *characters)
dropdown.pack()
button_explore = Button(root,
text = "Browse Files",
command = browseFiles)
label_file_explorer.pack(pady=10)
button_explore.pack(pady=10)
quitButton = tk.Button(text="Quit", command=root.destroy)
quitButton.pack(pady = 100)
root.mainloop()
def characterImage(*args):
##if imageAppear == True:
##clearImage()
path = pathlib.Path(__file__).parent.resolve()
path = path._str + "\\CharacterImages\\{}.jpg".format(selectedCharacter.get())
# path = path.replace("\\\\","\\")
path = Path(path)
characterImage = Image.open(path)
test = ImageTk.PhotoImage(characterImage)
label1 = tk.Label(image=test)
label1.image = test
# Position image
label1.pack()
imageAppear = True
def clearImage():
label1.config(image = "")
def browseFiles():
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Slippi Files",
"*.slp*"),
("All files",
"*.*")))
label_file_explorer.configure(text="File Opened: "+filename)
main()
imageAppear 检查已被注释掉,因为当前它甚至无法显示带有该检查的一张图像
附注我知道使用全局变量是不好的编码习惯,不需要因为使用它们而把我撕成碎片。
也许你应该尝试将这个应用程序变成面向对象的方法,这样你的全局就可以被“self”取代。 也许你的问题不是全局的,但它使代码有点混乱。