解決: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()

按下去終於達到我要的效果了……真不容易



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