Python 3 Tkinter: How to get a value/string from a Radiobutton inside a function?

Asked

Viewed 1,528 times

0

I would like to take selected sex value and print in the Datatargets window, but it doesn’t work, not even the other data typed as name or age. I have here a main window where will display two buttons: REGISTER and EXIT. The exit button does not have the command yet, but the registration yes, which is to open the SAVE window (located in the first def/function of the code. In this window that will open, there is a REGISTER button to display another window, DADOSSTARGETS as already mentioned before. It is in this window that I need my data typed in the fields (Entry) and the sex selected in Radiobutton to be saved with get() and displayed as text (Label) in this window.

from tkinter import *

def entrar():
  #Janela Principal
  janela = Tk()
  janela.title("Salvadados")
  janela.geometry('400x600')
  #Textos e entrada
  Lab1 = Label(janela, text='Nome completo:')
  Lab1.pack()
  textao = Entry(janela, textvariable = var,borderwidth= 5,relief ='ridge')
  textao.pack()
  Lab2 = Label(janela, text = 'Idade:')
  Lab2.pack()
  textao2 = Entry(janela, textvariable = d,borderwidth= 5,relief ='ridge')
  textao2.pack()
  Lab3 = Label(janela, text = "Sexo:")
  Lab3.pack()
  RBTN1 = Radiobutton(janela, text = 'Feminino',variable = kw,value = 'Feminino').pack()
  RBTN2 = Radiobutton(janela, text = 'Masculino', variable = kw, value = 'Maculino').pack()
  Lab4 = Label(janela, text = "Estado:")
  Lab4.pack()
  #Comando para o botão
  def janelanova():
     k = Tk()
     k.title("DadosSalvos")
     k.geometry('100x120')
     L2 = Label(k,text='Dados salvos:',bg='Red',fg='White')
     L2.pack()
     L = Label(k,text='')
     L.pack()
     L3 = Label(k,text='')
     L3.pack()
     L4 = Label(k,text='')
     L4.pack()
     b = var.get()
     t = d.get()
     g = kw.get()
     #para imprimir também(sem usar label)
     print(b)
     print(t)  
     print(g)
     L.config(text=b)
     L3.config(text= t)
     L4.config(text=g)
#JanPrincipal
janelaprincipal = Tk()
janelaprincipal.title('Menu Principal')
janelaprincipal.geometry('1010x200')
janelaprincipal['bg'] = '#C1FFC1'
mensagem1 = Label(janelaprincipal,text='Seja bem-vindo à Programação de Eventos do IFSP - Câmpus ----, cadastre-se para visualizar os eventos e suas programações completas.',font = ' -size 12',bg= 'green',fg='white')
mensagem1.place(x = 1,y= 14)
botaocadastro = Button(janelaprincipal,text= 'Cadastrar',font='-weight bold -size 16',fg='white', width = 20,activebackground='#B4EEB4',command=entrar)
botaocadastro['bg']='green'
botaocadastro.place(x = 355,y=60)
botaosair = Button(janelaprincipal,text = 'Sair',font='-weight bold -size 16',fg='white', width = 20,activebackground='#B4EEB4') 
botaosair['bg']='green'
botaosair.place(x = 355,y=120)
#Variáveis
var = StringVar()
d = StringVar()
var2 = StringVar()
kw = StringVar()
mainloop()
  • The question was not very clear @Mikalayla. And the demonization is not correct. You could try to be clearer and correct this?

  • Corrected question along with code.

1 answer

0

Hello @Mikalayla, the problem is that when creating the new screens used Tk().

By concept Tk() sets its main window, for other screens it is interesting to use Toplevel().

I didn’t make any major changes to your code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""""""
from tkinter import *
from tkinter import messagebox


def entrar():
    # Toplevel() porque já existe uma janela principal (janelaprincipal = Tk())
    janela = Toplevel()
    janela.title("Salvadados")
    janela.geometry('400x600')

    Lab1 = Label(janela, text='Nome completo:')
    Lab1.pack()
    textao = Entry(janela, textvariable=var, borderwidth=5, relief='ridge')
    textao.pack()

    Lab2 = Label(janela, text='Idade:')
    Lab2.pack()
    textao2 = Entry(janela, textvariable=d, borderwidth=5, relief='ridge')
    textao2.pack()

    Lab3 = Label(janela, text="Sexo:")
    Lab3.pack()

    # kw = StringVar()
    RBTN1 = Radiobutton(janela, text='Feminino', variable=kw, value='Feminino')
    RBTN1.pack()
    RBTN2 = Radiobutton(janela, text='Masculino', variable=kw, value='Masculino')
    RBTN2.pack()

    Lab4 = Label(janela, text="Estado:")
    Lab4.pack()

    # Botão que irá chamar a nova tela ou tkinter messagebox.
    btn_salvar = Button(janela, text='Salvar dados', command=lambda: janelanova(var, d, kw))
    btn_salvar.pack()

    btn_salvar = Button(janela, text='Salvar dados (messagebox)', command=lambda: janela_confirmacao(var, d, kw))
    btn_salvar.pack(pady=10)


def janelanova(var, d, kw):
    k = Toplevel()
    k.title("Salvadados")
    k.geometry('100x120')
    L2 = Label(k, text='Dados salvos:', bg='Red', fg='White')
    L2.pack()
    L = Label(k, text=var.get())
    L.pack()
    L3 = Label(k, text=d.get())
    L3.pack()
    L4 = Label(k, text=kw.get())
    L4.pack()


def janela_confirmacao(var, d, kw):
    msg = f'Dados que serão inseridos:\nNome: {var.get()}.\nIdade: {d.get()}\nSexo: {kw.get()}'
    resposta = messagebox.askokcancel(title='Confirmar?', message=msg)
    print(resposta)
    if resposta is True:
        print('Você clicou em OK')
    else:
        print('Você clicou em CANCELAR ou fechou a janela')


def sair():
    janelaprincipal.quit()


# JanPrincipal
janelaprincipal = Tk()
janelaprincipal.title('Menu Principal')
janelaprincipal.geometry('1010x200')
janelaprincipal['bg'] = '#C1FFC1'

mensagem1 = Label(janelaprincipal,
                  text='Seja bem-vindo à Programação de Eventos do IFSP -Câmpus Jacareí,'
                       'cadastre-se para visualizar os eventos e suas programações completas.',
                  font=' -size 12', bg='green', fg='white')
mensagem1.place(x=1, y=14)

botaocadastro = Button(janelaprincipal, text='Cadastrar', font='-weight bold -size 16',
                       bg='green', fg='white', width=20, activebackground='#B4EEB4', command=entrar)
botaocadastro.place(x=355, y=60)

botaosair = Button(janelaprincipal, text='Sair', font='-weight bold -size 16',
                   bg='green', fg='white', width=20, activebackground='#B4EEB4', command=sair)
botaosair.place(x=355, y=120)

# Variáveis
var = StringVar()
d = StringVar()
var2 = StringVar()
kw = StringVar()

mainloop()

I left the window you created to display the data and added a message box (messagebox) which performs the same function with the advantage of being able to check which button was pressed.

Remarks:

  • Whenever possible try to use clearer names that leave understood what each element performs. Even if the code gets a little more verbose.
  • In the future try to take a look at the Python documentation for Tkinter, because there are some examples of how to create code using classes, depending on the size of your application using classes can suit the code more readable and easy to maintain.

Example with classes using the your code as the basis:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exemplo"""

import tkinter as tk
from tkinter import messagebox


class TelaCadastro(tk.Toplevel):
    """Classe TelaCadastro 2 herda de tk.Toplevel()."""

    def __init__(self, **kw):
        """Construtor."""
        super().__init__(**kw)
        # Definindo a cor de fundo da janela (tk.Toplevel).
        self['background'] = '#E57373'
        # Título da janela.
        self.title(string='Tela de cadastro')
        # Denifindo um ícone diferente para nova janela.
        # icon_png = tk.PhotoImage(file='../icons/icon.png')
        # self.iconphoto(False, icon_png)

        # Tamanho da janela.
        width = round(self.winfo_screenwidth() / 2)
        height = round(self.winfo_screenheight() / 2)
        self.geometry(newGeometry=f'{width}x{height}')
        self.minsize(width=width, height=height)

        # Inserindo um frame sobre a janela para posicionar os widgets.
        # Não é obrigatório, contudo mantém organizado o layout.
        self.container = tk.Frame(master=self)
        self.container.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)

        self.criar_widgets()

    def criar_widgets(self):
        label_nome = tk.Label(master=self.container, text='Nome completo:', anchor=tk.W)
        label_nome.pack(fill=tk.X, padx=10)
        self.entry_nome = tk.Entry(master=self.container)
        self.entry_nome.pack(fill=tk.X, padx=10, pady=(0, 10))

        label_idade = tk.Label(master=self.container, text='Idade:', anchor=tk.W)
        label_idade.pack(fill=tk.X, padx=10)
        self.entry_idade = tk.Entry(master=self.container)
        self.entry_idade.pack(fill=tk.X, padx=10, pady=(0, 10))

        label_sexo = tk.Label(master=self.container, text='Sexo:', anchor=tk.W)
        label_sexo.pack(fill=tk.X, padx=10)

        self.kw = tk.StringVar()
        RADIOBUTTON = [('Feminino', 'Feminino'), ('Masculino', 'Masculino')]
        for texto, valor in RADIOBUTTON:
            radio_button = tk.Radiobutton(master=self.container, text=texto, variable=self.kw, value=valor, anchor=tk.W)
            radio_button.pack(fill=tk.X, padx=10)
        self.kw.set('Feminino')

        label_estado = tk.Label(master=self.container, text='Estado:', anchor=tk.W)
        label_estado.pack(fill=tk.X, padx=10, pady=(10, 0))

        button_salvar = tk.Button(self.container, text='Salvar registro', command=self.salva_registro)
        button_salvar.pack(pady=10)

    def salva_registro(self):
        msg = f'Dados que serão inseridos:\nNome: {self.entry_nome.get()}.\n' \
            f'Idade: {self.entry_idade.get()}\nSexo: {self.kw.get()}'
        resposta = messagebox.askokcancel(title='Confimar dados?', message=msg)
        print(resposta)
        if resposta is True:
            print('Você clicou em OK')
            self.destroy()
        else:
            print('Você clicou em CANCELAR ou fechou a janela')


class MeuApp(tk.Frame):
    """Classe herda de tk.Frame()"""

    def __init__(self, master=None):
        """Construtor"""
        super().__init__(master=master)
        self.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
        self.criar_widgets()

    def criar_widgets(self):
        mensagem1 = tk.Label(master=self,
                             text='Seja bem-vindo à Programação de Eventos do IFSP - Câmpus Jacareí.\n'
                                  'cadastre-se para visualizar os eventos e suas programações completas.')
        mensagem1.pack(expand=True, fill=tk.BOTH)

        botaocadastro = tk.Button(master=self, text='Cadastrar', command=self.abrir_tela_cadastro)
        botaocadastro.pack(fill=tk.X)

        botaosair = tk.Button(master=self, text='Sair', command=self.sair)
        botaosair.pack(fill=tk.X, pady=10)

    @staticmethod
    def abrir_tela_cadastro():
        TelaCadastro()

    def sair(self):
        self.master.quit()


root = tk.Tk()
root.title(string='Título do aplicativo')
# icon_png = tk.PhotoImage(file='../icons/icon.png')
# root.iconphoto(False, icon_png)
width = round(number=root.winfo_screenwidth() / 2)
height = round(number=root.winfo_screenheight() / 2)
root.geometry(newGeometry=f'{width}x{height}')
root.minsize(width=width, height=height)
app = MeuApp(master=root)
app.mainloop()

It is worth noting that there is no code that is right or wrong, they are just different forms/paradigms to solve the same problem.

  • The code gave error, said Toplevel was not set

  • I did a test with both code, including copying and pasting the answer code and the execution was normal. Make sure you are not having any error in the code edentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.