我在 tkinter 中创建了一个 2 Frames 应用程序,灵感来自 https://www.geeksforgeeks.org/how-to-change-the-tkinter-label-text/。目的是通过单击开始按钮导入新图像,并将其保存在 map.json 文件中。当我单击按钮时,框架会切换。但是,我想在单击按钮时查看 EditMenu 框架上的图像。由于该按钮位于主框架中,因此我找不到访问 EditMenu 中的标签的方法。
edit_frame.map_image_label = config(image=map_image)enter code here
行给出以下错误:NameError: name 'config' is not defined. Did you mean: 'self.config'?
PS:代码中的json部分暂时不起作用,不用关注
import json
import os
import shutil
from tkinter import *
from tkinter import filedialog, simpledialog
class Main(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.title("CS Memorizer")
self.state('zoomed')
container = Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (Home, EditMenu):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
frame = self.frames[Home]
frame.tkraise()
def save_image(self):
map_name = simpledialog.askstring("Map name", "Enter the name of the map.")
map_start_path = filedialog.askopenfilename()
file = open(map_start_path)
map_destination_path = os.getcwd() + "\\" + map_name + os.path.splitext(map_start_path)[1]
shutil.copyfile(map_start_path, map_destination_path)
with open("maps.json", "w+") as f:
if f.read() == "":
f.write(json.dumps({"maps": [1]}, indent=2))
edit_frame = self.frames[EditMenu]
edit_frame.tkraise()
map_image = PhotoImage(map_destination_path)
#Error !
edit_frame.map_image_label = configure(image=map_image)
class Home(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.config(background="skyblue")
maps_grid = Frame(self)
maps_grid.pack()
start_button = Button(maps_grid, text="Plus", command=lambda: controller.save_image())
start_button.grid(row=0, column=0)
class EditMenu(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
map_image_label = Label(self)
map_image_label.pack()
错误告诉您没有成功执行
config(image=map_image)
并建议您需要将其更改为
self.config(image=map_image)
在您共享的代码中找不到此内容,因此它一定在其他地方。您需要找到此代码并将
self.
添加到 config
。