Reputation: 537
I have been googling about this problem and couldn't find any good websites.... I want to create buttons and entry widget looks like:
[A] [B] [C] [D] [E] [F]
[ENTRYWIDGET HERE] [OK]
My code looks like:
class Controller(Frame):
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 )
And this looks completely different with what i'm trying to create..
Any feedbacks would be so grateful thanks.
Upvotes: 0
Views: 441
Reputation: 101032
You can just put your buttons into another Frame
.
Example:
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:
Edit to answer your comments
If you want to stick with for
loop for creating the buttons, a good way to apply the event handler is to create a mapping of button
<=> function to call
using a 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)
This way, it's easily extendable. If you don't care about the order of the buttons, you can just use
for letter, func in handler.items():
Upvotes: 2
Reputation: 82889
Alternatively, you could use another layout manager, e.g. using the grid()
method, which is a bit more expressive.
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)
Upvotes: 0