I'm developing a basic hexagon tile game in python3 tkinter (just for fun and learn). However, I can not find the way to parsing an attribute value (self.att_coord
) from an object (Hexagon
) to a tkinter widget (Label
) option called textvariable
. The idea is to show those values in the bottom widget, similar to show the coordinates of any board game.
So far, I can print() those values in the IDLE. The following code shows the reached so far (just copy/past/run).
Any help is appreciate.
import tkinter
import math
import random
class Hexagon:
"""
This class return the Geometric calculations to draw the hexagons
"""
def __init__(self, center_x, center_y, fit, size):
self.att_center_x = math.sqrt(3)*(fit+center_x*size)
self.att_center_y = (center_y*size)*(6/4)
self.att_size = size
self.att_coord = (center_x, center_y) #<--- Here the attribute values to parsing
self.att_polygone = self.met_polygon()
def __getitem__(self, x):
return getattr(self, x)
def met_polygon(self):
result = []
for i in range(0, 6):
angle_deg = 60*i+30
angle_rad = math.pi/180*angle_deg
result.append((self.att_center_x+self.att_size*math.cos(angle_rad),
self.att_center_y+self.att_size*math.sin(angle_rad)))
return result
class EofCanvas(tkinter.Canvas):
def __init__(self, master, *args, **kwargs):
tkinter.Canvas.__init__(self, master=master, *args, **kwargs)
self.att_current_coord = ""
def met_make_hexagon(self, hex_size):
hexa = Hexagon(1, 1, 0, hex_size)
x = self.create_polygon(hexa.att_polygone) #<--- Here hexagons are created
self.tag_bind(x, '<Enter>', lambda x, hexa = hexa:self.met_print_hexcoord(hexa))
def met_print_hexcoord(self, hexa=None):
self.att_current_coord = hexa.att_coord
print(self.att_current_coord) #<--- This print the attribute values to the IDLE
return hexa.att_coord
class UserInfoGame(tkinter.Frame):
def __init__(self, master, coord, *args, **kwargs):
tkinter.Frame.__init__(self, master=master, *args, **kwargs)
self.current = self.met_get_current_coord(coord)
self.att_coord_label = self.met_make_coord_label(coord)
def met_make_coord_label(self, coord):
label = tkinter.Label(self, width=10, textvariable=self.current) #<--- Here the textvariable
label.pack()
def met_get_current_coord(self, coord):
return coord.att_current_coord
class GameGUI:
def __init__(self):
self.root = tkinter.Tk()
self.root.attributes('-fullscreen', True)
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
canvas_game = EofCanvas(self.root, width=int(0.8*screen_width), height=(0.9*screen_height))
canvas_game.met_make_hexagon(40)
user_info_game = UserInfoGame(self.root, width=int(0.8*screen_width), height=int(0.1*screen_height), bd=1, relief='ridge', coord=canvas_game)
canvas_game.grid(column=1, row=1)
user_info_game.grid(column=1, rows=2)
def start(self):
self.root.mainloop()
if __name__ == '__main__':
appstart = GameGUI()
appstart.start()