Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Tkinter에서 이미지를 버튼으로 사용하는 방법은 무엇입니까?


이 예에서는 양식, 게임, 대화 상자 등과 같은 다른 많은 응용 프로그램에서 사용할 수 있는 둥근 버튼을 창에 만듭니다.

Tkinter에서 둥근 버튼을 만드는 가장 좋은 방법은 원하는 버튼 이미지를 사용하여 프레임에서 클릭 가능한 버튼으로 바꾸는 것입니다. PhotoImage()를 사용하면 실제로 가능합니다. 버튼의 원하는 이미지를 잡는 기능입니다.

따라서 다음 단계에서는 원하는 이미지를 버튼으로 만들고

  • 먼저 이미지를 클릭할 수 있게 만드는 데 사용할 수 있는 더미 버튼을 만듭니다.

  • PhotoImage(file) 함수를 사용하여 소스에서 이미지를 가져옵니다.

  • 이미지 파일을 Button 함수의 값으로 전달

  • borderwidth=0을 제거합니다.

  • 이제 버튼이 둥글게 되었습니다.

이 예에서는 이 이미지를 사용하여 클릭할 수 있게 만들 것입니다.

#Import all the necessary libraries
from tkinter import *

#Define the tkinter instance
win= Toplevel()
win.title("Rounded Button")

#Define the size of the tkinter frame
win.geometry("700x300")

#Define the working of the button

def my_command():
   text.config(text= "You have clicked Me...")

#Import the image using PhotoImage function
click_btn= PhotoImage(file='clickme.png')

#Let us create a label for button event
img_label= Label(image=click_btn)

#Let us create a dummy button and pass the image
button= Button(win, image=click_btn,command= my_command,
borderwidth=0)
button.pack(pady=30)

text= Label(win, text= "")
text.pack(pady=30)

win.mainloop()

출력

위의 코드를 실행하면 다음 출력이 생성됩니다 -

Tkinter에서 이미지를 버튼으로 사용하는 방법은 무엇입니까?