2017-03-03 201 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窗口一样。

伟大的部分是,你可以使用任何你喜欢的形状,而不仅仅是正常的按钮形状。

希望有帮助