tkinter是python的標準Tk GUI工具包的介面,在windows下如果你安裝的python3,那在安裝python的時候,就已經自動安裝了tkinter了
如果是在linux系統中,則不會自動安裝tkinter,需要通過
sudo apt-get install python-tk
手動安裝
首先先介紹一下,tkinter本身只支持gif等少數幾個圖片格式,如果圖片并不復雜,建議直接右擊圖片,進入編輯,在畫圖界面將圖片另存為gif格式就可以使用了(連png和jpeg都不支持,,,真的有點魔幻)


具體的編程操作
如果你嘗試直接重寫設定圖片的有關代碼會出問題
比如
import tkinter as tk
top = tk.Tk()
top.title("劃水摸魚") # 設定視窗
width = 260
height = 500
top.geometry(f'{width}x{height}') # 設定視窗大小
img_gif = tk.PhotoImage(file='./動作/問號.gif') # 設定圖片
label_img = tk.Label(top, image=img_gif) # 設定預顯示圖片
label_img.place(x=30, y=120)
def change_img(): # 設定按鈕事件
img_gif0 = tk.PhotoImage(file='./動作/走.gif')
label_img.configure(image=img_gif0)
label_img.place(x=30, y=120)
button = tk.Button(top, text='Prediction', command=change_img) # 設定按鈕
button.place(x=90, y=330)
top.mainloop()
在這里我直接重寫了label_img,但是實際效果是
問號.gif能夠正常顯示,

點擊按鈕后,走.gif無法顯示

實際切換圖片,應該用configure實作
正確的操作如下
import tkinter as tk
top = tk.Tk()
top.title("劃水摸魚") # 設定視窗
width = 260
height = 500
top.geometry(f'{width}x{height}') # 設定視窗大小
img_gif = tk.PhotoImage(file='./動作/問號.gif') # 設定圖片
img_gif0 = tk.PhotoImage(file='./動作/走.gif')
label_img = tk.Label(top, image=img_gif) # 設定預顯示圖片
label_img.place(x=30, y=120)
def change_img():
label_img.configure(image=img_gif0) # 設定按鈕事件
button = tk.Button(top, text='Prediction', command=change_img) # 設定按鈕
button.place(x=90, y=330)
top.mainloop()
具體效果

點擊按鈕后

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/273726.html
標籤:python
