你如何在 tkinter 画布上创建一个按钮? [英] How do you create a Button on a tkinter Canvas?

查看:65
本文介绍了你如何在 tkinter 画布上创建一个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个框架,然后创建了一个画布.
我接下来要做的是在画布上添加一个按钮.
但是,当我打包 Button 时,我看不到 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!

这是我尝试过的:

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

推荐答案

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

The Tkinter pack manager tries to resize the parent widget to the correct size to contain its child widgets, and no larger, by default. So the canvas is there - but it's precisely the same size as the button, and thus invisible.

如果你想在画布上放置一个小部件而不导致画布动态调整大小,你需要Canvas.create_window()函数:

If you want to place a widget on a canvas without causing the canvas to dynamically resize, you want the Canvas.create_window() function:

# ... 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) 的按钮,而不调整画布本身的大小.

This will create your button with upper-left corner at (10, 10) relative to the canvas, without resizing the canvas itself.

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

Note that you could replace the window argument with a reference to any other Tkinter widget. One caveat, though: the named widget must be a child of the top-level window that contains the canvas, or a child of some widget located in the same top-level window.

这篇关于你如何在 tkinter 画布上创建一个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆