我為一個按鈕準備了兩張圖片,同時我還創建了帶圖片的按鈕。我想在我第一次點擊它的時候改變按鈕的影像。例如,當我點擊按鈕時,我想讓按鈕的影像從 "UnclickedImage "變成 "ClickedImage",
。我無法在stackoverflow中找到任何類似的問題,
。from tkinter import *
class Example(Frame)。
def __init__(self, tk=None)。
super().__init__()
self.tk = tk
self.init_ui()
def init_ui(self)。
self.photoTodo = PhotoImage(file="./Images/TodoUnClicked.png"/span>)
Button(self.tk, image=self.photoTodo).pack(side=LEFT)
self.photoStayFocussed = PhotoImage(file="./Images/StayFoccusedUnClicked.png")
Button(self.tk, image=self.photoStayFussed).pack(side=RIGHT)
def main()。
root = Tk()
root.configure(bg='white')
ex = Example(root)
root.title('')
root.iconbitmap('./Images/empty.ico')
root.geometry("400x100 300 300")
root.mainloop()
if __name__ == '__main__'/span>:
main()
uj5u.com熱心網友回復:
你可以用一個自定義的按鈕類來做這件事。
class ImageButton(Button)。
def __init__(self, master, image1, image2, *args, **kwargs)。
self.unclickedImage = PhotoImage(file = image1)
self.clickedImage = PhotoImage(file = image2)
super().__init__(master, *args, image = self.unclickedImage, **kwargs)
self.toggleState=1。
self.bind("<Button-1>", self.clickFunction)
def clickFunction(self, event = None) 。
if self.cget("state") != "disabled": #Ignore click if button is disabled: 忽略點擊。
self.toggleState *= -1。
if self.toggleState == -1:
self.config(image = self.clickedImage)
else:
self.config(image = self.unclickedImage)
這是以widget master以及第一和第二張圖片路徑為引數,創建PhotoImage物件,然后用未點擊的圖片實體化一個按鈕。
有一個與<Button-1>的系結,它是左鍵點擊,當按鈕被點擊時,這將改變影像。toggleState變數跟蹤當前顯示的影像,所以當按鈕被點擊時,會顯示相反的影像。
你可以像這樣把它納入你當前的程式中:
from tkinter import *
class ImageButton(Button)。
def __init__(self, master, image1, image2, *args, **kwargs)。
self.unclickedImage = PhotoImage(file = image1)
self.clickedImage = PhotoImage(file = image2)
super().__init__(master, *args, image = self.unclickedImage, **kwargs)
self.toggleState=1。
self.bind("<Button-1>", self.clickFunction)
def clickFunction(self, event = None) 。
if self.cget("state") != "disabled": #Ignore click if button is disabled: 忽略點擊。
self.toggleState *= -1。
if self.toggleState == -1:
self.config(image = self.clickedImage)
else:
self.config(image = self.unclickedImage)
class Example(Frame)。
def __init__(self, master, *args, **kwargs)。
super().__init__(master, *args, **kwargs)
self.init_ui()
def init_ui(self)。
ImageButton(self, "./Images/TodoUnClicked.png", "./Images/TodoClicked.png").pack(side=left)
ImageButton(self, "./Images/StayFoccusedUnClicked.png", "./Images/StayFoccusedClicked.png").pack(side=RIGHT)
def main()。
root = Tk()
root.configure(bg='white')
ex = Example(root)
ex.pack(fill = "both", expand = True)
root.title('')
root.geometry("400x100 300 300")
root.mainloop()
if __name__ == '__main__'/span>:
main()
注意,我還修正了你的Example類,因為你使用它的方式不太正確。當你繼承一個 tkinter 物件時,你把主物件傳給 super().__init__,然后用 self 作為子物件的父物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/319455.html
標籤:
