views:

81

answers:

2

How do I randomly add buttons to a Tkinter GUI? I need it to be able to create a button, then put it anywhere on the window, is this possible? I am using Python 2.6 on Windows.

+2  A: 

If you want random button placement (or anything not aligned along a grid, etc.), you can use the place geometry manager. Depending on platform, overlapped buttons may not behave as you expect, though, so you may want to avoid them.

Here's a simple example:

from Tkinter import *
from random import random

root = Tk()
frame = Frame(root, height=200, width=200)

for i in range(10):
    Button(frame, text=str(i)).place(x=random() * 150, y=random() * 180)

frame.pack()
root.mainloop()
Nicholas Riley
OK, I like this. It work pretty good. But, how do I avoid overlapping buttons? I don't want that at all. Is it possible to make them evenly spaced as well?
Zachary Brown
Well, they wouldn't be random then, would they? :-) If you want more evenly spaced buttons, use the grid geometry manager (http://effbot.org/tkinterbook/grid.htm). Otherwise, you will need to handle intersections yourself.
Nicholas Riley
The reason I need them random is I don't kow how many buttons it will need to create. It may be 1 the first time, but 10 the next. I just need them to look good, but not overlap at all. How would I handle intersections? If that is what I need to do, I am open to learning.
Zachary Brown
Oh, random *number* of buttons, not random *position*. You did not make that clear :-) You should be able to figure out a way to do it with grid - put the buttons on top of each other, next to each other, etc. Grid will never overlap buttons.
Nicholas Riley
I thought I needed random positions. Sorry, I figured out I was wrong on that one. I have been playing around with grid(), but no luck so far.
Zachary Brown
I guess what I need is the buttons scattered throughout the window.
Zachary Brown
A: 

There are several options to choose from. For example, you could design on a grid where you have six buttons per row. Then it's just a matter of starting at row 0, incrementing the column for each button. When you get to the last column, reset the column to 0 and increment the row by one.

Another option is to use a text widget as the container, and embed your buttons in the text widget with wrapping enabled. With this trick the buttons will fill a row automatically and wrap if the user grows or shrinks the main windows. It's a tiny bit more work, but it works well if that's the behavior you want.

Bryan Oakley