0

How can I change a global variable to a value inputted by a user in an entry field?

card_no = 0

def cardget():
    global card_no
    card_no = e1.get()
    print(card_no)


def menu():
    global card_no
    root = Tk()

    e1 = Entry(root).pack()
    Label(root, text= "Enter card number").pack(anchor= NW)
    Button(root, text= "Confirm card", command=cardget).pack(anchor= NW)

menu()
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
Mathew Wright
  • 15
  • 1
  • 7
  • `e1` is `None`, not an `Entry` widget, if it was such a widget it still wouldn't be visible in `cardget`, and there's no `mainloop()` in your code, which means you're probably running this from the interactive interpreter. – TigerhawkT3 Oct 07 '16 at 10:07
  • http://stackoverflow.com/q/1101750/7432 – Bryan Oakley Oct 07 '16 at 13:04

1 Answers1

1

Don't use global variables. Tkinter apps work much better with OOP.

import tkinter as tk

class App:
    def __init__(self, parent):
        self.e1 = tk.Entry(parent)
        self.e1.pack()
        self.l = tk.Label(root, text="Enter card number")
        self.l.pack(anchor=tk.NW)
        self.b = tk.Button(root, text="Confirm card", command=self.cardget)
        self.b.pack(anchor=tk.NW)
        self.card_no = 0
    def cardget(self):
        self.card_no = int(self.e1.get()) # add validation if you want
        print(self.card_no)

root = tk.Tk()
app = App(root)
root.mainloop()
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97