0

I'm still trying to understand classes. I have used a class to easily initialize several identical labels and entry box widgets. Here is my code:

import tkinter as tk

class Tile:
    def __init__(self, master, row_number, text_entry):
        item = tk.Label(master, fg="white", bg="#300000",
                        text="Tile # " + text_entry + ":",
                        font=("Arial", 14, "bold"))
        user_input = tk.Entry(master, width=50)
        item.grid(column=0, row=rows, padx=(0, 30), pady=(0, 10))
        user_input.grid(column=1, row=row_number, padx=(0, 30), pady=(0, 10))
        self.ent = user_input.get()

I was under the impression that I could use "self.ent = user_input.get()" to get the user input from the entry widget within my Tile object:

example = Tile(root,5,"5")

# then later have a button to call this action:

def button_clicked():
    print(example.ent)

This isn't working... How can I achieve this goal?

YangTegap
  • 381
  • 1
  • 11
  • You retrieved the value from the Entry *immediately* after creating it. There WAS NO USER INPUT YET, how could there possibly have been anything typed in that millisecond or so? You need to do the `.get()` later, in `button_clicked()` for example. – jasonharper Sep 15 '20 at 04:36
  • Does this answer your question? [Why is Tkinter Entry's get function returning nothing?](https://stackoverflow.com/questions/10727131/why-is-tkinter-entrys-get-function-returning-nothing) – Karthik Sep 15 '20 at 04:36
  • You need to bind the entry widget to a string var and then call the `.get()` method on it as a stringVar updates every time there is a change, so there is no need for a button cclick or any other event to update it. check [this] (https://effbot.org/tkinterbook/entry.htm) – psycoxer Sep 15 '20 at 04:39

1 Answers1

0

You could make ent a property of the Tile class. This way the get method will be called each time you try to read ent

class Tile:
    def __init__(self, master, row_number, text_entry):
        item = tk.Label(master, fg="white", bg="#300000",
                        text="Tile # " + text_entry + ":",
                        font=("Arial", 14, "bold"))
        user_input = tk.Entry(master, width=50)
        item.grid(column=0, row=rows, padx=(0, 30), pady=(0, 10))
        user_input.grid(column=1, row=row_number, padx=(0, 30), pady=(0, 10))

    @property
    def ent(self):
        return user_input.get()

Then you just do print(example.ent) as before and it will print the current value of the user_input field

scotty3785
  • 6,763
  • 1
  • 25
  • 35
  • Maybe I'm missing something, but when I do this the property is unable to call user_input – YangTegap Sep 16 '20 at 02:40
  • @YangTegap Can you share the error message? You didn't share enough code for me to be able to execute the code so I had to guess and the code is untested – scotty3785 Sep 16 '20 at 07:22