2017-03-03 284 views
2

我想爲我的腳本使用tkinter得到舍入按鈕。圓形按鈕tkinter python

我發現下面的代碼:

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() 

你需要通過在構造函數的定義,即parentwidthheightcolor中定義的參數。

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"和按鈕邊框將被刪除。

我加了self.roundedborder["bg"] = "white"這樣背景背景的按鈕就和Tkinter窗口一樣。

偉大的部分是,你可以使用任何你喜歡的形狀,而不僅僅是正常的按鈕形狀。

希望有幫助