Home > Blockchain >  having problems with Tkinter and Entry.get()
having problems with Tkinter and Entry.get()

Time:04-27

I need some help

I have ben trying to make a calculator program in python and I did pretty good.

I wanted to use the same code and the Tkinter library to make a window for it but it has me so confused.

my calculator code is:

while True:

    num1 = 0
    num2 = 0
    num3 = 0
    
    print("Enter your calculation:")
    calc_in = str(input()).split()
    
    try:
        num1 = int(calc_in[0])
        op1 = calc_in[1]
        num2 = int(calc_in[2])
    except:
        print("Error: Make sure you typed your sum correctly")
        continue
        
    try:
        op2 = calc_in[3]
        num3 = int(calc_in[4])
    except:
        pass
    
    if op1 == " ":
        answer = num1   num2
    elif op1 == "-":
        answer = num1 - num2
    elif op1 == "*":
        answer = num1 * num2
    elif op1 == "/":
        answer = num1 / num2
    
    try:
        if op2 == " ":
            answer = answer   num3
        elif op2 == "-":
            answer = answer - num3
        elif op2 == "*":
            answer = answer * num3
        elif op2 == "/":
            answer = answer / num3
    except:
        pass
    
    print(answer)

And the code works ok but when I tried to use an entry widget for tinker it game me some weird thing back.

this is the code with Tkinter so far (i don't have the tkinter output bit yet cause i wanted to see if it would actually work):

import tkinter as tk
import tkinter.ttk as ttk

window = tk.Tk()

label = tk.Label(
    text="Calculator",
    foreground="white",
    background="dodgerBlue",
    width=15,
    height=0,
    font=("Arial", 25),
)
label.pack()

calc_input = tk.Entry(
    foreground="dodgerBlue",
    background="white",
    width=15,
    font=("Arial", 25),
)
calc_input.pack()

window.mainloop()

while True:
    num1 = 0
    num2 = 0
    num3 = 0

    convert = str(calc_input.get)
    
    calc_in = convert.split()
    
    print(calc_in)
    break

    try:
        num1 = int(calc_in[0])
        op1 = calc_in[1]
        num2 = int(calc_in[2])
    except:
        print("Error: Make sure you typed your sum correctly")
        continue
        
    try:
        op2 = calc_in[3]
        num3 = int(calc_in[4])
    except:
        pass
    
    if op1 == " ":
        answer = num1   num2
    elif op1 == "-":
        answer = num1 - num2
    elif op1 == "*":
        answer = num1 * num2
    elif op1 == "/":
        answer = num1 / num2
    
    try:
        if op2 == " ":
            answer = answer   num3
        elif op2 == "-":
            answer = answer - num3
        elif op2 == "*":
            answer = answer * num3
        elif op2 == "/":
            answer = answer / num3
    except:
        pass
    
    print(answer)

When I click enter nothing happens but when I close the window I get a weird array:

['<bound', 'method', 'Entry.get', 'of', '<tkinter.Entry', 'object', '.!entry>>']

I don't understand what is happening so any help would be greatly appreciated.

CodePudding user response:

Your code has two major problems.

  1. First: calc_input.get This line of code is wrong because you do not call the function where you need to use this calc_input.get()
  2. Second: After calc_input.get()this line of code you get an error _tkinter.TclError: invalid command name ".!entry" Because you try to get the value from the input box after the window is destroyed.

Formated code is here

import tkinter as tk
import tkinter.ttk as ttk
convert = 0
window = tk.Tk()

label = tk.Label(
    text="Calculator",
    foreground="white",
    background="dodgerBlue",
    width=15,
    height=0,
    font=("Arial", 25),
)
label.pack()

calc_input = tk.Entry(
    foreground="dodgerBlue",
    background="white",
    width=15,
    font=("Arial", 25),
)
calc_input.pack()
def on_closing():
    global convert # Exccess to the global variable which  is define in line 3.
    convert = calc_input.get() # set the value to convert
    window.destroy() # destroy the window
    
window.protocol('WM_DELETE_WINDOW',on_closing) # This is execute when someone try to exit or destroy the window And call the on_closing function

window.mainloop()

while True:
    num1 = 0
    num2 = 0
    num3 = 0

    
    calc_in = convert.split()
    
    print(calc_in)
    break

    try:
        num1 = int(calc_in[0])
        op1 = calc_in[1]
        num2 = int(calc_in[2])
    except:
        print("Error: Make sure you typed your sum correctly")
        continue
    
        
    try:
        op2 = calc_in[3]
        num3 = int(calc_in[4])
    except:
        pass
    
    if op1 == " ":
        answer = num1   num2
    elif op1 == "-":
        answer = num1 - num2
    elif op1 == "*":
        answer = num1 * num2
    elif op1 == "/":
        answer = num1 / num2
    
    try:
        if op2 == " ":
            answer = answer   num3
        elif op2 == "-":
            answer = answer - num3
        elif op2 == "*":
            answer = answer * num3
        elif op2 == "/":
            answer = answer / num3
    except:
        pass
    
    print(answer)

I am solve the same problem yesterday yo can take a look link.

CodePudding user response:

You have to remember in each GUI app, all the things you should do, have to be before(or inside) your mainloop(), because it is the nature of GUI apps, they are a loop and check the state of the app.

I saw your code and notice a lot of mistakes:

After mainloop() function you write some code (While loop). Each code after mainloop() will be executed after you close the window and you should keep in your mind that widgets will be destroyed after you close the window. So this is why should I said you have to all you want inside you mainloop() function.

If you want to get your Entry value, you can add a button and by clicking on button you can print the value of the entry. (of course you should read the instructions of command attribute in Button)

Remember, each widget have to get the root(or window as you write in your code) as the first argument. For instance Label(window, "This is Label").

And finally: In a while loop, when you write break command, the rest of the code never be executed. So all those try except blocks, never be executed.

And this is an example that I wrote for you with your widget style:

class MainWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.label = tk.Label(self,
                          text="Calculator",
                          foreground="white",
                          background="dodgerBlue",
                          width=15,
                          height=0,
                          font=("Arial", 25),
                          )
        self.label.pack()

        self.entry = tk.Entry(self,
                          foreground="dodgerBlue",
                          background="white",
                          width=15,
                          font=("Arial", 25),)
        self.entry.pack()

        self.button = tk.Button(self, text="Print Value",
                            command=self.print_entry_value)
        self.button.pack()

        self.mainloop()

    def print_entry_value(self) -> None:
        """
        This widget will print the entry value
        """

        value = self.entry.get()
        print(value)


if __name__ == "__main__":
    window = MainWindow()
  • Related