Python | Cómo cambiar dinámicamente el texto de Checkbutton

Tkinter es un módulo GUI (interfaz gráfica de usuario) que se utiliza para crear varios tipos de aplicaciones. Viene junto con Python y consta de varios tipos de widgets que se pueden usar para hacer que la GUI sea más atractiva y fácil de usar. El botón de verificación es uno de los widgets que se utiliza para seleccionar múltiples opciones.

El botón de verificación se puede crear de la siguiente manera:

chkbtn = ttk.Checkbutton(parent, value = options, ...)

Código #1:

# This will import tkinter and ttk
from tkinter import * from tkinter import ttk
  
root = Tk()
  
# This will set the geometry to 200x100
root.geometry('200x100')
  
text1 = StringVar()
text2 = StringVar()
  
# These text are used to set initial
# values of Checkbutton to off
text1.set('OFF')
text2.set('OFF')
  
chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1,
                          offvalue = 'GFG Not Selected',
                          onvalue = 'GFG Selected')
  
chkbtn1.pack(side = TOP, pady = 10)
chkbtn2 = ttk.Checkbutton(root, textvariable = text2, variable = text2,
                          offvalue = 'GFG Average',
                          onvalue = 'GFG Good')
chkbtn2.pack(side = TOP, pady = 10)
  
root.mainloop()

Salida n.º 1: cuando ejecuta la aplicación, ve los estados iniciales del botón de verificación como se muestra en la salida.

Salida n.º 2: tan pronto como seleccione el botón Verificar , verá que el texto se ha cambiado como en la salida.

Salida n.º 3: cuando anule la selección del botón de verificación , volverá a observar los siguientes cambios.

Código n.º 2: los comandos se pueden integrar con el botón de verificación , que se puede ejecutar cuando se selecciona o deselecciona el botón de verificación según las condiciones.

# Importing tkinter, ttk and
# _show method to display
# pop-up message window
from tkinter import * from tkinter import ttk
from tkinter.messagebox import _show
  
root = Tk()
root.geometry('200x100')
  
text1 = StringVar()
text1.set('OFF')
  
# This function is used to display
# the pop-up message
def show(event):
    string = event.get()
    _show('Message', 'You selected ' + string)
  
chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1,
                          offvalue = 'GFG Good',
                          onvalue = 'GFG Great',
                          command = lambda : show(text1))
chkbtn1.pack(side = TOP, pady = 10)
  
root.mainloop()

Salida:

Nota: En el código anterior, offvalue y onvalue se usan para establecer los valores del botón de verificación del estado no seleccionado y el estado seleccionado, respectivamente.

Publicación traducida automáticamente

Artículo escrito por sanjeev2552 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *