python - How do I make text(one letter) fill out a tkinter button? -
i have tic tac toe game i'm trying put finishing touches on. each tile in game button letter 'x' or 'o'. can't seem letters fill out frame. when change font size, buttons bloat out. if try set tile height/weight after setting font size doesn't seem have effect.
is there way make 'x' expand out fill button it's in?
class tictactoeboard(frame): def __init__(self, parent=none, game=none): frame.__init__(self, parent) # controlling gui through external game class. self.game = game self.symbol = game.sym() mainframe = ttk.frame(root, padding=(12, 12, 12, 12)) mainframe.grid(column=0, row=0, sticky=(n, w, e, s)) # how change tile player plays on. self.strvars = [stringvar() x in range(9)] # setup button tiles self.buttons = [] i, s in enumerate(self.strvars): func = (lambda i=i: self.btn_press(i)) b = button(mainframe, textvariable=s, font='size, 35', command=func) b.config(height=5, width=10) self.buttons.append(b) # add each tile grid x in range(3): y in range(3): self.buttons.pop(0).grid(row=x, column=y)
i there no way make characters automatically fill entire button's space. consider canvas
objects instead of button
s. there can draw x (two lines) , o (circle) full control on size , space between edge of canvas , sign. maybe makes sense make field in ui own class.
from functools import partial itertools import cycle import tkinter tk class fieldui(tk.canvas): def __init__(self, parent, size, variable): tk.canvas.__init__(self, parent, width=size, height=size) self.size = size self.variable = variable self.variable.trace('w', self.update_display) self.update_display() def update_display(self, *_args): self.delete(tk.all) value = self.variable.get() if value == 'x': self.create_line(5, 5, self.size - 5, self.size - 5, width=4) self.create_line(self.size - 5, 5, 5, self.size - 5, width=4) elif value == 'o': self.create_oval(5, 5, self.size - 5, self.size - 5, width=4) elif value != '': raise valueerror("only 'x', 'o', , '' allowed") class gameui(tk.frame): def __init__(self, parent): tk.frame.__init__(self, parent, background='black') self.symbols = cycle('xo') self.field_vars = [tk.stringvar() _ in range(9)] i, field_var in enumerate(self.field_vars): field_ui = fieldui(self, 50, field_var) field_ui.bind('<button-1>', partial(self.on_click, i)) column, row = divmod(i, 3) field_ui.grid(row=row, column=column, padx=1, pady=1) def on_click(self, field_index, _event=none): field_var = self.field_vars[field_index] if not field_var.get(): field_var.set(next(self.symbols)) def main(): root = tk.tk() game_ui = gameui(root) game_ui.pack() root.mainloop() if __name__ == '__main__': main()
Comments
Post a Comment