Search code examples
pythontkintertkinter-entrytkinter-buttoncustomtkinter

Is there a way to have a function that returns the argument as a string in tkinter?


import customtkinter as ctk
import tkinter as tk
from tkinter import ttk

def get_var(input):
    input.get()

entry_var = ctk.StringVar()
entry_box = ctk.CTkEntry(
    root,
    textvariable = entry_var
    ).grid(row = 0, column = 0)

submit_button = ctk.CTkButton(
    root,
    text = "Submit entry",
    command = get_var(entry_var)
    ).grid(row = 1, column = 0)

.get() isn't recognized unless I use a stringvar from tkinter. I'm clueless as to why. Could anyone educate me and help me understand?

Is there no way to accept the argument as the tk.stringvar? or am I just doing something wrong?


Solution

  • I'm not 100% familiar with CustomTkinter, but it vanilla tkinter the geometry manager methods grid, pack, and place all return None. As written, your widgets are evaluating to None and therefore won't respond to get(). Also, input is a reserved word for the input function - you should use another name here.

    You also need to modify the command argument for submit_button. As written, it's going to call get_var immediately, which isn't what you want. You can avoid this by using a lambda or by modifying get_var to just call entry_var.get() directly (this is my preferred approach, since you don't have to pass in the entry_box widget).

    def get_var():  # no need to pass in the widget
        return entry_var.get()  # just call 'get' directly
        # you'll probably want to do something with the value other than just 'return'
        # it, but this is an example...
    
    
    entry_var = ctk.StringVar()
    entry_box = ctk.CTkEntry(
        root,
        textvariable=entry_var
    )
    entry_box.grid(row = 0, column = 0)  # do this on a separate line
    
    submit_button = ctk.CTkButton(
        root,
        text="Submit entry",
        command=get_var,  # pass the function by name here, no parens ()
    )
    submit_button.grid(row = 1, column = 0)  # do this on a separate line