Simple board game GUI framework

Terry Reedy tjreedy at udel.edu
Mon Sep 11 13:12:49 EDT 2017


On 9/11/2017 10:12 AM, Paul Moore wrote:

> Thanks for the information. That's more or less the sort of thing I
> was thinking of. In fact, from a bit more browsing, I found another
> way of approaching the problem - rather than using pygame, it turns
> out to be pretty easy to do this in tkinter.

I was going to suggest tkinter.

> The following code is basically the core of what I need:
> 
> import tkinter as tk
> 
> def create_board(root):
>      board = {}
>      for r in range(8):
>          for c in range(8):
>              lbl = tk.Button(bg="white", text="   ", font=("Consolas", 12))
>              lbl.grid(row=r, column=c)
>              board[r,c] = lbl
>      return board
> 
> root = tk.Tk()
> board = create_board(root)
> root.mainloop()

Mainloop is a blocking call, and while it is running, one can only 
interact with the data and gui in ways that one has already programmed. 
If you run the above with python -i, or equivalently, from an IDLE 
editor, you will not see a >>> prompt until you close the tk windows, at 
which point there is nothing left to interact with.

> That creates an 8x8 grid of white buttons. With this, I can make a
> button red simply by doing
> 
> board[3,2]["bg"] = "red"

However, if you run the code above from an IDLE editor, you can omit or 
comment out the mainloop call and still see the board, because IDLE's 
run code calls tk's update in a non-blocking manner about 20 times a 
second.  Without mainloop running, you immediately get a >>> prompt and 
can interact with the gui in a live exploratory fashion.  You can enter 
statements like the color assignment above, and the background updates 
will make them quickly take effect.

(I just opened https://bugs.python.org/issue31421 to document this.)

> That's really all I need. With that I can place objects on the grid by
> asking them for their colour and x/y co-ordinates. Add a bit of driver
> logic, and I have a display system. We can then spend the time working
> on how we add business logic to the classes (movement, collision
> detection, etc...)
> 
> I really need to spend some time looking into tkinter. I very rarely
> think of it when developing code, and yet whenever I do it's amazingly
> easy to put together a solution quickly and easily.

-- 
Terry Jan Reedy




More information about the Python-list mailing list