解决:python中把label.configure在函数里就无效(点击按钮改变图片)

写了个关于图片的工具的界面,想点按钮图片变一下,没想到就遇到两个坑折腾了2天……分享一下

(ps:错误原理直接代码里=========的注释看)

基本测试代码,显示个图片

from tkinter import *
root = Tk()  #创建窗口
 
photo = PhotoImage(file='pic.png')#pic.png就在工程目录里(和.py在同一个文件夹)
img_label = Label(root, imag=photo).pack()
 
root.mainloop()

嗯……没问题,下一步。


接下来贴个按钮,加个按下要触发的函数

from tkinter import *
root = Tk()  
 
photo = PhotoImage(file='pic.png')
img_label = Label(root, imag=photo).pack()

def start():#===========================================================从这里
    photo1 = PhotoImage (file='start.png')
    img_label.configure(imag=photo1)

button_img = Button(root,text = '开始',command=start).pack()#==========加到这里

root.mainloop()

乍一看没问题,特喵的2个大坑!!!!



1.直接pack()会出现【AttributeError: 'NoneType' object has no attribute 'configure'】错误

按下去直接报错!


感谢https://zhidao.baidu.com/question/391953023941782205.html【解答见:“最佳”答案下的评论】

from tkinter import *
root = Tk()  
 
photo = PhotoImage(file='pic.png')
img_label = Label(root, imag=photo)
img_label.pack()#独立.pack出来!<=====================

def start():
    photo1 = PhotoImage (file='start.png')
    img_label.configure(imag=photo1)

button_img = Button(root,text = '开始',command=start).pack()

root.mainloop()

以为解决了?图样图森破!(接楼下图)摁下去不报错,但是什么都没有出来!


2.图片不globle,会显示不出来(蜜汁错误)

(运行楼上改报错后的代码后按下按钮)???按下去后我的图呢?


感谢https://bbs.csdn.net/topics/390878480

from tkinter import *
root = Tk()  
 
photo = PhotoImage(file='pic.png')
img_label = Label(root, imag=photo)
img_label.pack()

def start():
    global img_label,photo1#要改的label、替换的图片,缺一不可都要global引用!<=======================
    photo1 = PhotoImage (file='start.png')
    img_label.configure(imag=photo1)

button_img = Button(root,text = '开始',command=start).pack()

root.mainloop()

按下去终于达到我要的效果了……真不容易



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章