2017-03-03 6 views
2

나는 tkinter를 사용하여 스크립트를위한 둥근 버튼을 얻으려고합니다. 둥근 버튼 tkinter 파이썬

는 다음 코드 발견 :

from tkinter import * 
import tkinter as tk 

class CustomButton(tk.Canvas): 
    def __init__(self, parent, width, height, color, command=None): 
     tk.Canvas.__init__(self, parent, borderwidth=1, 
      relief="raised", highlightthickness=0) 
     self.command = command 

     padding = 4 
     id = self.create_oval((padding,padding, 
      width+padding, height+padding), outline=color, fill=color) 
     (x0,y0,x1,y1) = self.bbox("all") 
     width = (x1-x0) + padding 
     height = (y1-y0) + padding 
     self.configure(width=width, height=height) 
     self.bind("<ButtonPress-1>", self._on_press) 
     self.bind("<ButtonRelease-1>", self._on_release) 

    def _on_press(self, event): 
     self.configure(relief="sunken") 

    def _on_release(self, event): 
     self.configure(relief="raised") 
     if self.command is not None: 
      self.command() 
app = CustomButton() 
app.mainloop() 

을하지만, 나는 다음과 같은 오류 얻을 :

TypeError: __init__() missing 4 required positional arguments: 'parent', 'width', 'height', and 'color' 

답변

1

당신은 생성자에 인수를 전달되지 않습니다.

정확하게,이 라인

app = CustomButton() 

에 당신은 즉 parent, width, heightcolor 생성자 정의에 정의 된 인수를 전달해야합니다.

2

루트 창 (또는 다른 위젯)을 먼저 만들고 다른 매개 변수와 함께 CustomButton에 제공해야합니다 (__init__ 정의 참조).

대신 다음 app = CustomButton()의 시도 :

app = tk.Tk() 
button = CustomButton(app, 100, 25, 'red') 
button.pack() 
app.mainloop() 
+1

감사합니다. 그건 실행했지만 버튼이 둥근 아니 –

+1

아니, 아니에요. 그러나 정확히 "발견 한"코드가 수행해야하는 작업입니다. 그것은 기복이있는 사각 캔버스를 만들고 그것에 타원을 그립니다. 버튼을 눌렀다 떼면 안도가 올라가고 다시 올립니다. – avysk

3

매우 쉬운 방법은 Tkinter에 둥근 버튼 이미지를 사용하는 것입니다 수 있도록.

첫째는 아래와 같이 반올림됩니다 그래서 당신이 .PNG로 저장하고 외부에서 배경을 제거처럼 당신에게 버튼을 원하는 이미지 생성 :

Click here to see image

다음 이미지를 삽입을 이 같은 PhotoImage와 버튼에 :

self.loadimage = tk.PhotoImage(file="rounded_button.png") 
self.roundedbutton = tk.Button(self, image=self.loadimage) 
self.roundedbutton["bg"] = "white" 
self.roundedbutton["border"] = "0" 
self.roundedbutton.pack(side="top") 

border="0"를 사용할 수 있는지 확인하고 버튼의 테두리가 제거됩니다.

단추의 배경이 Tkinter 창과 같도록 self.roundedborder["bg"] = "white"을 추가했습니다.

큰 부분은 일반적인 단추 모양뿐만 아니라 원하는 모양을 사용할 수 있다는 것입니다.

희망이 도움이 되었습니까?