如何解决使用 PhotoImage 以字典值的形式调用地址的问题
我发现 Python 编码有问题 我用 askopenfilename 方法打开一个文件。然后我想用另一个函数以图像的形式以字典值的形式调用文件的地址。命令直接在函数中是没有问题的,比如类中的key。但是当我把这些命令放到另一个函数中去调用并在另一个函数(第三个函数)中使用它的变量时,就出现了问题,出现了错误。
我发现 Python 编码有问题 我用 askopenfilename 方法打开一个文件。然后我想用另一个函数以图像的形式以字典值的形式调用文件的地址。命令直接在函数中是没有问题的,比如类中的key。但是当我把这些命令放到另一个函数中去调用并在另一个函数(第三个函数)中使用它的变量时,就出现了问题,出现了错误。
def __init__(self):
self.value=0
self.dic_img={}
self.root=Tk()
self.root.iconphoto(self.root,PhotoImage(file="python_logo.png"))
self.root.title("Python.Test")
self.root.geometry("600x600+450+120")
self.root.config(bg="#e0c25c")
def main_titel(self):
self.lab1=Label(self.root,text="Image Album",font=('Yu Gothic',35,'bold','underline'),bg='#e0c25c',fg='#664477')
self.lab1.pack()
self.lab1.place(x=150,y=20)
def Add_Button(self):
self.icon=PhotoImage(file="img4.png")
self.b= Button(self.root,image=self.icon,borderwidth=0,bg="#e0c25c",fg='#e0c25c',activebackground="#e0c25c",width=100,height=99)
self.b.pack()
self.b.place(x=60,y=115)
self.b.config(command=self.Add_b_func)
def Add_b_func(self):
self.my_filetypes=[('PNG Img file','.PNG')]
self.Adr_file=filedialog.askopenfilename(parent=self.root,initialdir=os.getcwd(),title="Please select a file",filetypes=self.my_filetypes)
self.dic_img[self.value]=self.Adr_file
#print(self.dic_img)
self.value+=1
self.lab1.config(text=("%d" %self.value))
def next_Button(self):
self.icon1=PhotoImage(file="next4.png")
self.b1= Button(self.root,image=self.icon1,width=50,height=44)
self.b1.pack()
self.b1.place(x=500,y=450)
def back_Button(self):
self.icon2=PhotoImage(file="back3.png")
self.b2= Button(self.root,image=self.icon2,height=44)
self.b2.config(command=self.Back_b_func)
self.b2.pack()
self.b2.place(x=50,y=450)
def Back_b_func(self):
print(self.dic_img)
def f_lab (self):
self.lab1=Label(self.root,text=("%d" %self.value),30,'bold'),bg='white',fg='black',width=10,height=2)
self.lab1.pack()
self.lab1.place(x=250,y=110)
def f_lab_dis(self):
self.lab_dis=Label(self.root,text="Value the Picture",12,width=15,height=1)
self.lab_dis.pack()
self.lab_dis.place(x=300,y=220)
def f_lab_img(self):
self.icon_img=PhotoImage(file = self.Adr_file)
self.lab_img=Label(self.root,image=self.icon_img)
self.lab_img.pack()
self.lab_img.place(x=120,y=350)
def m_loop(self):
self.root.mainloop()
解决方法
问题是在你的主函数中:
def main():
root=my_gui()
root.main_titel()
root.Add_Button()
root.f_lab()
root.f_lab_dis()
root.back_Button()
root.next_Button()
root.f_lab_img()
root.m_loop()
f_lab_img()
在 Add_b_func
之前被调用。 Add_b_func
设置为由按钮执行的 command
,但仅在单击按钮时执行。因为它只是稍后执行,所以当 f_lab_img
被调用时,self.Adrr_file
还没有值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。