简体   繁体   中英

Tkinter with OOP python

My goal is to get a very basic GUI with two tabs where the first one has the options of log in, register a new user and unregister this user. If i want to click to the second option (register the user or called "darse de alta") it should appear a second window (and closing the first one) where i can put my information to register (name, dni and phone number). Then the last point of this program should be adding this new user to a database called self.socios. This is because in the method "agregar" inside the class Registro_socios whenever i want to register a new user he has to be added to the database. I don't know how to connect the new user with the class previously created. Thanks to anyone who can explain and clarify in some way.

class Socio:
    
    def __init__(self,nombre_socio,dni,telefono):
        self.nombre = nombre_socio
        self.dni = dni
        self.telefono = telefono
    
    def __str__(self):
        return "Nombre: {0}\nDNI: {1}\nTelefono: {2}".format(self.nombre,self.dni,self.telefono)

class Registro_socios: 
    
    def __init__(self,baseDatos_socios = None):
        if baseDatos_socios is None:
            baseDatos_socios = {} # Diccionario vacío con DNIs como Keys
            self.socios = baseDatos_socios
    
    def agregar(self,socio):
        if self.existe(socio): # En el caso que existe retorne True
            raise KeyError(f'{socio.__class__.__name__} ya existente') # A Python KeyError exception is what is raised when you try to access a key that isn't in a dictionary ( dict )
        self.socios[socio.dni] = socio
    
    def existe(self,socio):
        if socio.dni in self.socios:
            return True
        return False

root = tk.Tk()
miFrame = Frame(root) 
# miFrame = Frame(root,width=1000,height=500) 
miFrame.pack()

def alta_socio():
    otra_ventana = tk.Toplevel(root)
    miFrame2 = Frame(otra_ventana)
    miFrame2.pack()
    
    texto_nombreUsuario = Entry(miFrame2).grid(row=0,column=1, padx=5, pady=5)
    nombre_usuario = Label(miFrame2, text='Nombre de socio: ').grid(row=0,column=0, padx=5, pady=5)

    texto_DNI = Entry(miFrame2).grid(row=1,column=1, padx=5, pady=5)
    nombre_usuario = Label(miFrame2, text='DNI: ').grid(row=1,column=0, padx=5, pady=5)

    texto_nombreUsuario = Entry(miFrame2).grid(row=2,column=1, padx=5, pady=5)
    nombre_usuario = Label(miFrame2, text='Teléfono de contacto: ').grid(row=2,column=0, padx=5, pady=5)
    
    root.iconify() 

botonInicio = Button(root, text='Entrar',bg='orange')
botonInicio.pack()

boton_AltaSocio = Button(root, text='Darse de alta',bg='orange', command=alta_socio) 
boton_AltaSocio.pack()

boton_BajaSocio = Button(root, text='Darse de baja',bg='orange', command=baja_socio)
boton_BajaSocio.pack()

root.mainloop()

I see many mistakes here. The first one is you call the mainwindow with tk.Tk() and the frames as Frame , so I imagine that you are importing tkinter twice like this:

import tkinter as tk
from tkinter import *

Forget the second import and put the tk before each widget.

Then the Button 'dar-se baja' calls a method that is not defined.

Inside the alta_socio method you are doing this:

texto_nombreUsuario = tk.Entry(miFrame2).grid(row=0,column=1, padx=5, pady=5)

This is bad because while the tk.Entry() returns an instance of the class Entry, the Entry.grid() method does not return anything. so texto_nombeUsuario will be None and you will not to be able to access what is in the entry widget. You should do like this instead:

texto_nombreUsuario = tk.Entry(miFrame2)
texto_nombreUsuario.grid(row=0,column=1, padx=5, pady=5)

Another option is to use a StringVar:

texto_nombreUsuario = tk.StringVar(root)
tk.Entry(miFrame2, textvariable=texto_nombreUsuario).grid(row=0,column=1, padx=5, pady=5)

For the third Entry in alta_socio() you are using for the telephone the same variable you used for the name. Fix it. Finally you can add a tk.Button that will call a method which will create a Socio . Like:

tk.Button(miFrame2, text='Confirmar', command=add_socio).grid()

The method add_socio() can be a nested method from alta_socio() this way it will have access to the variables texto_nombreUsuario , texto_DNI and texto_telefono . It get the text from texto_nombreUsuario with the command texto_nombreUsuario.get() and call the previously created classes:

def alta_socio():
    def add_socio(): # this function is nested so it can access variables defined in alta_socio
        nombre = texto_nombreUsuario.get()
        tel = texto_telefono.get()
        dni = texto_dni.get()
        socio = Socio(nombre, dni, telefono) # here you call the Socio class previously defined

    otra_ventana = tk.Toplevel(root)
    miFrame2 = tk.Frame(otra_ventana)
    miFrame2.pack()
    
    texto_nombreUsuario = tk.StringVar(root) # this is a tkinter variable which contains the user name
    # this entry saves it values in the tkinter variable above:
    tk.Entry(miFrame2, textvariable=texto_nombreUsuario).grid(row=0,column=1, padx=5, pady=5)
    tk.Label(miFrame2, text='Nombre de socio: ').grid(row=0,column=0, padx=5, pady=5)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM