Is it possible to draw a BUTTON?

Rick Johnson rantingrickjohnson at gmail.com
Wed Jul 27 21:59:23 EDT 2016


On Wednesday, July 27, 2016 at 7:15:20 PM UTC-5, MRAB wrote:
> On 2016-07-28 00:13, huey.y.jiang at gmail.com wrote:
> > On Wednesday, July 27, 2016 at 4:18:29 PM UTC-4, huey.y... at gmail.com wrote:
> >> Hi Folks,
> >>
> >> It is common to put a BUTTON on a canvas by the means of coding. However, in my application, I need to draw a circle on canvas, and then make this circle to work as if it is a button. When the circle is clicked, it triggers a new image to be displayed. Somebody can help? Thanks!
> >
> > ---> By the way, the GUI is TK.
> >
> Here's a simple example:
> 
> 
> #! python3.5
> # -*- coding: utf-8 -*-
> import tkinter as tk
> 
> def mouse_clicked(event):
>      dist_sq = (event.x - circle['x']) ** 2 + (event.y - circle['y']) ** 2
> 
>      if dist_sq <= circle['radius'] ** 2:
>          print('Clicked inside circle')
> 
> root = tk.Tk()
> 
> canvas = tk.Canvas(root, width=400, height=200)
> canvas.pack()
> 
> circle = dict(x=60, y=60, radius=20)
> 
> left = circle['x'] - circle['radius']
> top = circle['y'] - circle['radius']
> right = circle['x'] + circle['radius']
> bottom = circle['y'] + circle['radius']
> 
> canvas.create_oval((left, top, right, bottom), outline='red', fill='red')
> canvas.bind('<Button-1>', mouse_clicked)
> 
> root.mainloop()

I didn't try your code, but you can simply it by using some of the core functionality provided via "canvas.tag_bind(...)"

## START CODE ##
import Tkinter as tk

def cb_canvasButton(event):
    print 'You clicked me using button {0}'.format(event.num)
    canvas.move('button', 10, 10) # Little extra surprise!

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.create_oval(10,10,50,50, outline='red', fill='blue',
                   tags=('button',)
                   )
canvas.tag_bind('button', '<Button>', cb_canvasButton)
canvas.pack()

root.mainloop() 
## END CODE ##



More information about the Python-list mailing list