Ctkinter. How do you set the curser in the entry widget and and output when "Enter" is pressed?

68 views Asked by At

Please help me, I am trying to set the curser in the entry widget and when I press "enter" the word "yay" appears in the "name" entry widget in a frame class. I have tried everything but can't seem to succeed. The end result will be when an account number is entered the details are fetched from a data file and displayed apon hitting "Enter". My code below:

import customtkinter as ctk
import keyboard

ctk.set_appearance_mode("dark")


class Frame1(ctk.CTkFrame):
    def __init__(self, master):
        super().__init__(master)
        # self.word = ""

        self.name = ctk.CTkLabel(self, text="Name", fg_color="transparent")
        self.name.grid(row=1, column=0, padx=10, pady=10, sticky="w")

        self.name_x = ctk.CTkEntry(self, width = 300, placeholder_text="")     
        self.name_x.grid(row=1, column=1, padx=10, pady=10, sticky="e")


   
class App(ctk.CTk):
    def __init__(self):
        super().__init__()

        self.title("CRD Master")
        self.geometry("1000x650")
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.acc_no = ctk.CTkEntry(self, width = 60, placeholder_text="Acc. no.")
        self.acc_no.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        # self.button = ctk.CTkButton(self, width = 60, text="get", command=self.button_callback)
        # self.button.grid(row=0, column=0, padx=10, pady=10, sticky="e")

        self.frame = Frame1(self)
        self.frame.grid(row=1, column=0, padx=10, pady=(10, 0), sticky="nsw")
        self.frame.name_x.focus_set()
        self.frame.name_x.bind("<Return>", command=self.keypress) 
        
    def keypress(self, event):
        word = "yay" 
        key = event.keycode
        if key == "Return":
            self.frame.name_x.insert(0, word)
 
app=App()
app.mainloop()

I tried moving the keypress function, bind and focus statements into the frame class. These statements are being ignored no matter where they are.

1

There are 1 answers

0
nokla On BEST ANSWER

The problem with your code is that the keycode is a number and not a string. So, when the Enter key is pressed it enters the keypress and reaches to if key == "Return": but never execute what inside the if block.

The function keypress is only called when you press the Enter key so there is no need to check that.

The following should work:

    def keypress(self, event):
        word = "yay"
        self.frame.name_x.insert('0', word)

In addition, if you want the word to replace what the user wrote in the entry you should use the delete method:

    def keypress(self, event):
        word = "yay"
        self.frame.name_x.delete("0", "end")
        self.frame.name_x.insert("0", word)