0

Inside of my program there is a definition that opens a window (this window is the code below) in this window I want to be able to set a variable using an entry box and then outside of window be able to call that variable with the set integer.

To test my code there is an accept and test button. If I can type in a number, press accept then press test it should print that number. currently it prints class int.

from tkinter import *
fuel_stored = int

def Accept():
    Varible = number1.get()
    fuel_stored = Variable
    print (Varible)

def PrintFuel():
    print (fuel_stored)

root = Tk()
root.geometry=("100x100+100+50")

number1 = Entry(root, bg="white")
number1.pack()
number1.focus_force()


nameButton = Button(root, text="Accept", command=Accept)
nameButton.pack(side=BOTTOM, anchor=S)
nameButton = Button(root, text="Test", command=PrintFuel)
nameButton.pack(side=BOTTOM, anchor=S)


root.mainloop()

1 Answers1

2

There are some "problems" with your code.

Typo

See your Accept() function. There is an a missing in the first and third line.

Difference between global and local variables

Your script use the global object fuel_stored declared in line 2. Your Accept() declares another local fuel_stored object that is different from the first one. A function or methode in Python will always (implicite) use the local version of an object. The solution is to tell your function to use the global object with the keyword global like this

def Accept():
    Variable = number1.get()
    print (Variable)
    global fuel_stored
    fuel_stored = Variable

See also Using global variables in a function for this.

Different solution with content variable

Here I offer you a full different solution using a content variable. The Entry() object know use fuel_stored directly. See parameter textvariable= in the contstructor of Entry. I also minimized your code a bit.

#!/usr/bin/env python3
from tkinter import *

def PrintFuel():
    print (fuel_stored.get())

root = Tk()

# Need to be instanciated it after Tk().
fuel_stored = StringVar()

number1 = Entry(root, textvariable=fuel_stored)
number1.pack()

nameButton = Button(root, text="Test", command=PrintFuel)
nameButton.pack()

root.mainloop()
buhtz
  • 10,774
  • 18
  • 76
  • 149