Tkinter入门
前页 | Chapter 12. The Button Widget | 后页

# Patterns

Plain buttons are pretty straightforward to use. Simply specify the button contents (text, bitmap, or image) and a callback to call when the button is pressed:

        b = Button(master, text="OK", command=self.ok)

A button without a callback is pretty useless; it simply doesn't do anything when you press the button. You might wish to use such buttons anyway when developing an application. In that case, it is probably a good idea to disable the button to avoid confusing your beta testers:

        b = Button(master, text="Help", state=DISABLED)

If you don't specify a size, the button is made just large enough to hold its contents. You can use the `padx` and `pady` option to add some extra space between the contents and the button border. You can also use the `height` and `width` options to explicitly set the size. If you display text in the button, these options define the size of the button in text units. If you display bitmaps or images instead, they define the size in pixels (or other screen units). You can actually specify the size in pixels even for text buttons, but it takes some magic. Here's one way to do it (there are others):

        f = Frame(master, height=32, width=32)
        f.pack_propagate(0) # don't shrink
        b = Button(f, text="Sure!")
        b.pack(fill=BOTH, expand=1)

Buttons can display multiple lines of text (but only in one font). You can use newlines or the `wraplength` option to make the button wrap text by itself. When wrapping text, use the `anchor`, `justify`, and possibly `padx` options to make things look exactly as you wish. An example:

        b = Button(master, text=longtext, anchor=W, justify=LEFT, padx=2)

To make an ordinary button look like it's held down, for example if you wish to implement a toolbox of some kind, you can simply change the relief from RAISED to SUNKEN:

        b.config(relief=SUNKEN)

You might wish to change the background as well. Note that a possibly better solution is to use a `Checkbutton` or `Radiobutton` with the `indicatoron` option set to false:

        b = Checkbutton(master, image=bold, variable=var, indicatoron=0)

前页 | Home | 后页
The Button Widget | Up | Methods