0

我一直在谷歌上搜索这个问题,找不到任何好的网站......我想创建按钮和条目小部件,如下所示:

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

[在此输入小工具] [确定]

我的代码如下所示:

类控制器(框架):

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 )

这看起来与我正在尝试创建的完全不同..

任何反馈将不胜感激。

4

2 回答 2

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

结果:

结果

编辑以回答您的评论

如果您想坚持使用for循环来创建按钮,应用事件处理程序的一个好方法是使用 a创建button<=>的映射:function to calldict

    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():
于 2012-10-05T07:01:54.797 回答
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)
于 2012-10-05T08:13:58.717 回答