如何在tkinter Canvas上创建Button?

时间:2012-08-16 04:39:09

标签: python user-interface button tkinter

我创建了一个Frame,然后创建了一个Canvas 我接下来要做的是在画布上添加一个按钮 但是,当我打包按钮时,我看不到画布!

以下是我的尝试:

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

3 个答案:

答案 0 :(得分:13)

Tkinter pack管理器尝试将父窗口小部件的大小调整为正确的大小以包含其子窗口小部件,默认情况下不会更大。所以画布就在那里 - 但它与按钮的大小完全相同,因此是不可见的。

如果您想在不使用的画布上放置窗口小部件,导致画布动态调整大小,您需要Canvas.create_window()函数:

# ... snip ...
button1 = Button(self, text = "Quit", command = self.quit, anchor = W)
button1.configure(width = 10, activebackground = "#33B5E5", relief = FLAT)
button1_window = canvas1.create_window(10, 10, anchor=NW, window=button1)

这将创建相对于画布的左上角为(10, 10)的按钮,而不会调整画布本身的大小。

请注意,您可以使用对任何其他Tkinter小部件的引用替换window参数。但有一点需要注意:命名小部件必须是包含画布的顶级窗口的子级,或者是位于同一顶级窗口中的某个小部件的子级。

答案 1 :(得分:3)

你可以使用button1.place(x = 0,y = 0)几何管理器而不是pack(side = TOP) pack调整主窗口小部件的大小以使其足够大以容纳子窗口小部件

http://effbot.org/tkinterbook/pack.htm#Tkinter.Pack.pack_propagate-method

http://effbot.org/tkinterbook/place.htm

答案 2 :(得分:0)

我有完全相同的问题。我不知道官方的方法,但是有一种解决方法:

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