I am definitely not an Tkinter expert, this is my first Tkinter app.
But here is my proposal how to use Python class inheritance to organize your solution.
The code runs
import Tkinter
import tkFont as font
class Gui(Tkinter.Tk):
def __init__(self, logic):
Tkinter.Tk.__init__(self)
self.logic = logic
self.geometry("370x170")
self.resizable(width=False, height=False)
rock_button = Tkinter.Button(self, text="Rock", command=self.rock_clicked)
rock_button.place(width=100, height=30, x=10, y=30)
paper_button = Tkinter.Button(self, text="Paper", command=self.paper_clicked)
paper_button.place(width=100, height=30, x=10, y=70)
scissors_button = Tkinter.Button(self, text="Scissors", command=self.scissors_clicked)
scissors_button.place(width=100, height=30, x=10, y=110)
score_font = font.Font(family="Helvetica", size=20)
own_score_lbl = Tkinter.Label(self, text="0", relief=Tkinter.RIDGE, font=score_font)
own_score_lbl.place(width=50, height=110, x=120, y=30)
ai_score_lbl = Tkinter.Label(self, text="0", relief=Tkinter.RIDGE, font=score_font)
ai_score_lbl.place(width=50, height=110, x=200, y=30)
ai_choice = Tkinter.Label(self, relief=Tkinter.RIDGE)
ai_choice.place(width=100, height=110, x=260, y=30)
self.render_title()
def render_title(self):
logic = self.logic
templ = "Rock({logic.rock_counter}), Paper({logic.paper_counter}), Scissors({logic.scissors_counter})"
title = templ.format(logic=logic)
self.title(title)
def rock_clicked(self):
self.logic.play_rock()
self.render_title()
def paper_clicked(self):
self.logic.play_paper()
self.render_title()
def scissors_clicked(self):
self.logic.play_scissors()
self.render_title()
class GameLogic():
def __init__(self):
self.rock_counter = 0
self.paper_counter = 0
self.scissors_counter = 0
def play_rock(self):
self.rock_counter += 1
def play_paper(self):
self.paper_counter += 1
def play_scissors(self):
self.scissors_counter += 1
logic = GameLogic()
game = Gui(logic)
game.mainloop()
Gui Inheriting from Tkinter.Tk
- we get all the methods from Tk, incl.
mainloop
Using Gui __init__
constructor
First, we ask our parent class to initialize, this is the Tkinter.Tk.init(self)
Then we refer to former root
as self
.
Adding logic to Gui
Logic
is implemented as independent class, it knows noting about frontend, it only expects calls to it's methods.
We instantiate logic
in advance and pass it to Gui constructore.
There must be a contract, what methods and properties is Logic going to provide.
Using Logic from Gui
When Gui finds out, there is some logic related event, it can call methods of logic
.
After changes of the logic, it is often needed (withing Gui method) to rerender something.
Start that up
This shall be the patter to follow:
- instantiate logic
- create gui, passing the logic in
- let it run
translated to Python:
logic = GameLogic()
game = Gui(logic)
game.mainloop()