Python创建Buttons和Entry小部件

时间:2012-10-05 05:14:12

标签: python tkinter

我一直在谷歌搜索这个问题,找不到任何好的网站.... 我想创建按钮和条目小部件看起来像:

  

[A] [B] [C] [D] [E] [F]

     

[ENTRYWIDGET HERE] [OK]

我的代码如下:

  

类控制器(框架):

def __init__(self,parent):
    Frame.__init__(self, parent)
    self.parent = parent
    self.button1 = Button(parent, text = "A")
    self.button1.pack(side = TOP)
    self.button1 = Button(parent, text = "B")
    self.button1.pack(side = TOP)
    self.button1 = Button(parent, text = "C")
    self.button1.pack(side = TOP)
    self.button1 = Button(parent, text = "D")
    self.button1.pack(side = TOP)
    self.button1 = Button(parent, text = "E")
    self.button1.pack(side = TOP)
    self.button1 = Button(parent, text = "F")
    self.button1.pack(side = TOP)

    self.myentrybox = Entry(parent, width = 50)
    self.myentrybox.pack(side = LEFT)
    self.button = Button(parent, text = "OK")
    self.button.pack(side = RIGHT )

这与我正在努力创造的东西完全不同......

任何反馈都会非常感谢。

2 个答案:

答案 0 :(得分:2)

您只需将按钮放入另一个 Frame


示例:

from Tkinter import *
from ttk import *

class Controller(Frame):

    def __init__(self,parent):
        Frame.__init__(self, parent)

        buttons = Frame(parent)
        buttons.pack(side=TOP)
        for letter in 'ABCDEF':
            Button(buttons, text=letter).pack(side=LEFT)

        Entry(parent, width=50).pack(side=LEFT)
        Button(parent, text='OK').pack(side=RIGHT)

root = Tk()
app = Controller(root)
root.mainloop()

<强>结果:

Result

编辑以回答您的评论

如果您想坚持使用for循环来创建按钮,则应用事件处理程序的一种好方法是创建button&lt; =&gt;的映射。 function to call使用dict

    handler = {'A': function_A,
               'B': function_FooBar,
               'C': function_SomeThing}

    for letter, func in ((k, handler[k]) for k in sorted(handler)):
        Button(buttons, text=letter, command=func, width=10).pack(side=LEFT)

这样,它很容易扩展。如果您不关心按钮的顺序,可以使用

for letter, func in handler.items():

答案 1 :(得分:0)

或者,您可以使用其他布局管理器,例如使用grid()方法,这种方法更具表现力。

def __init__(self,parent=None):
    Frame.__init__(self, parent)
    self.grid()
    # create buttons in row 1
    for i, c in enumerate("ABCDEF"):
        self.button = Button(parent, text=c)
        self.button.grid(row=1, column=i+1)
    # create textfield and 'ok' in row 2    
    self.myentrybox = Entry(parent, width = 50)
    self.myentrybox.grid(row=2, column=1, columnspan=6)
    self.button = Button(parent, text = "OK")
    self.button.grid(row=2, column=7)