Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a Button on a tkinter Canvas?

I created a Frame and then a Canvas.
What I want to do next is to add a Button on the Canvas.
However, when I packed the Button I cannot see the Canvas!

Here is what I tried:

from Tkinter import Tk, Canvas, Frame, Button
from Tkinter import BOTH, W, NW, SUNKEN, TOP, X, FLAT, LEFT

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Layout Test")
        self.config(bg = '#F0F0F0')
        self.pack(fill = BOTH, expand = 1)
                #create canvas
        canvas1 = Canvas(self, relief = FLAT, background = "#D2D2D2",
                                            width = 180, height = 500)
        canvas1.pack(side = TOP, anchor = NW, padx = 10, pady = 10)
        #add quit button
        button1 = Button(canvas1, text = "Quit", command = self.quit,
                                                            anchor = W)
        button1.configure(width = 10, activebackground = "#33B5E5",
                                                        relief = FLAT)
        button1.pack(side = TOP)

def main():
    root = Tk()
    root.geometry('800x600+10+50')
    app = Example(root)
    app.mainloop()

if __name__ == '__main__':
    main()
like image 432
Tong Avatar asked Aug 16 '12 04:08

Tong


1 Answers

I had the exact same problem. There isn't an official way that I know, but here's a way around it:

from Tkinter import *
root = Tk()
def clicked(event):
    print("pressed")
canvas1 = Canvas(root, relief = FLAT, background = "#D2D2D2")
canvas1.pack()
buttonBG = canvas1.create_rectangle(0, 0, 100, 30, fill="grey40", outline="grey60")
buttonTXT = canvas1.create_text(50, 15, text="click")
canvas1.tag_bind(buttonBG, "<Button-1>", clicked) ## when the square is clicked runs function "clicked".
canvas1.tag_bind(buttonTXT, "<Button-1>", clicked) ## same, but for the text.
root.mainloop()
like image 64
user10370643 Avatar answered Oct 11 '22 21:10

user10370643