Reputation: 11
I'm trying to make a save and load function in a checkers game. The save and load function is already given, I only need to make the buttons and make it work in an tkinter interface.
Here's the 2 functions given:
def sauvegarder(self, nom_fichier):
try:
with open(nom_fichier, "w") as f:
f.write("{}\n".format(self.couleur_joueur_courant))
f.write("{}\n".format(self.doit_prendre))
if self.position_source_forcee is not None:
f.write("{},{}\n".format(self.position_source_forcee[0],self.position_source_forcee[1]))
else:
f.write("None\n")
f.writelines(self.damier.convertir_en_chaine())
except:
raise ProblemeSauvegarde("Problème lors de la sauvegarde.")
def charger(self, nom_fichier):
try:
with open(nom_fichier) as f:
self.couleur_joueur_courant = f.readline().rstrip("\n")
doit_prendre_string = f.readline().rstrip("\n")
if doit_prendre_string == "True":
self.doit_prendre = True
else:
self.doit_prendre = False
position_string = f.readline().rstrip("\n")
if position_string == "None":
self.position_source_forcee = None
else:
ligne_string, colonne_string = position_string.split(",")
self.position_source_forcee = (int(ligne_string), int(colonne_string))
self.damier.charger_dune_chaine(f.read())
except:
raise ProblemeChargement("Problème lors du chargement.")
In the file where I'm working in the interface here goes the 2 functions that I wrote:
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
from dames.partie import Partie
from dames.exceptions import PositionSourceInvalide, PositionCibleInvalide
class InterfaceDamier(tk.Frame):
def __init__(self, parent, taille_case, damier):
"""taille_case est la taille d'un côté d'une case en pixels."""
# Definition du damier : # de cases
self.n_lignes = 8
self.n_colonnes = 8
# Definition du damier : taille des cases (en pixels)
self.taille_case = taille_case
# Defiz«nition du damier : couleur de cases
self.couleur1 = "white"
self.couleur2 = "gray"
# Pièces sur le damier, on utilise le damier de la classe damier
self.damier = damier
# Calcul de la taille du dessin
canvas_width = self.n_colonnes * self.taille_case
canvas_height = self.n_lignes * self.taille_case
# Initialisation de la fenêtre parent contenant le canvas
tk.Frame.__init__(self, parent)
# Initialisation du canvas
self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, width=canvas_width, height=canvas_height,
background="white")
# On place le canvas et le plateau (self) à l'aide de "grid".
self.canvas.grid(padx=2, pady=2, sticky=tk.N + tk.S + tk.E + tk.W)
self.grid(padx=4, pady=4, sticky=tk.N + tk.S + tk.E + tk.W)
# Fait en sorte que le redimensionnement de la fenêtre redimensionne le damier
self.canvas.bind("<Configure>", self.actualiser)
##test sam
self.piecesJoue ={}
self.frame2 = ""
def charger_fichier(self):
#fonction pour charger une partie déjà jouée à partir d'un fichier texte
nom_fichier = tk.filedialog.askopenfilename(filetypes = [("Fichiers Texte","*.txt")])
if len(nom_fichier) > 0:
self.partie = Partie(nom_fichier)
self.pieces = {}
for position, piece in self.game.interfaceDames.InterfaceDamier.items():
nom = self.obtenir_nom_piece_selon_caractere(str(piece))
self.addpiece(nom, position[0], position[1], "blanc")
self.frame2.destroy()
self.frameMenu.destroy()
self.piecesJoue.clear()
self.__init__(self, parent)
self.canvas.bind("<Configure>", self.actualiser)
def sauvegarder_fichier(self):
"fonction pour enregistrer une partie de jeu dans un fichier texte "
mesformats = [("Fichiers Texte","*.txt")]
root = Tkinter.Tk()
nom_fichier = tk.FileDialog.asksaveasfilename(parent=root,filetypes = [mesformats],title="Sauvegarder la partie sous...")
if len(nom_fichier) > 0:
self.Partie.sauvegarder(nom_fichier)
The buttons seems to work, but it always get me the same error in the 2 functions which is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python32\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
TypeError: charger() takes exactly 2 arguments (1 given)
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python32\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
TypeError: sauvegarder() takes exactly 2 arguments (1 given)
I think it's probably something missing in the init, but I don't find it. (A lot of the function names and instructions are write in french, sorry about that)
Upvotes: 0
Views: 1557
Reputation: 78
It would be helpful if I had your full source code (may put in pastebin or something) but, it sounds like you got something like
myButton = tk.Button(text='A Button!', command=charger)
This won't work because of the way the button callback works. Tkinter can't (as far as I can tell) send any arguments this way. There's a mix of different callback formats in Tkinter. If you bind and event like
<<Modified>>
to a command, Tkinter will expect a one argument function, with the first (and only) argument being the event Tkinter intercepted. The button expects nothing. In order to get this to work, you might use lambda, partial (from functool) or function wrappers. If I had a button in a class that needed to open (you'll have to forgive me--I don't speak French), I might do this like:
myButton = tk.Button(text='A Better Button!', command = lambda: charger(self.someFileName))
Depending on your implementation, partial may work better, or who knows. But you'll need something like this to utilize your save/open functions the way you have them now, if I am reading you right.
I hope this helps, and if it doesn't, maybe post some more source code and we'll figure it out.
Upvotes: 2