Search code examples
python-3.xtkintertkinter-entry

Mapping Tkinter entry box to variable in python 3.8


I am a complete beginner in python,I was hoping someone could help me figure out what I am trying to accomplish.

I built a small tkinter front end that will generate a string multiple times. I want the amount of times that the string is generated to be based off of an entry box. I have hit a wall.

Here is my Front End (help_FE.py)

from tkinter import *
import help_BE
def view_formula():
    text1.delete('1.0',END)
    text1.insert(END,help_BE.End_result)
pass

window = Tk()
window.wm_title=("Print:")
l1=Label(window,text = "Page to print:")
l1.grid(row=3, column=2)
e1 = Entry(window)
e1.grid(row=3, column=3)
text1=Text(window, height=20,width=35)
text1.grid(row=4,column=3, rowspan=10, columnspan=7, padx=5, pady=10)
sb1=Scrollbar(window)
sb1.grid(row=4,column=11,rowspan=10)
text1.configure(yscrollcommand=sb1.set)
sb1.configure(command=text1.yview)
text1.bind('<<TextboxSelect>>')
b1=Button(window, text = "Generate", width =10, command=view_formula)
b1.grid(row=3,column=6)

window.mainloop()

and my backend (help_BE.py)

currently, the generate button will print "Testing" 3 times, because i have set pages = 3 in the backend, but I want to be able to set pages to whatever is entered into the frontend entry box.

pages = 3
result=[]
def foo():
    skip_zero = pages + 1
for x in range (skip_zero):
if x==0:
continue
        result.append("Testing"+str(x))

    listToStr = ''.join([str(element) for element in result])
    full_formula = (listToStr)
return full_formula

End_result = foo()

Solution

  • The data inputted in the field can be accessed using the function Entry.get(), and you can convert the string to a number with the int function. In order to get it to the backend, and in order to keep your value up to date, I would make sure that, as jasonharper mentioned, you call foo each time the button is pressed, passing the entry's value in as the argument pages. This means tweaking your code as such:

    help_BE.py

    def foo(pages):
        skip_zero = pages + 1
        for x in range (skip_zero):
            if x==0:
                continue
            result.append("Testing"+str(x))
        listToStr = ''.join([str(element) for element in result])
        full_formula = (listToStr)
    return full_formula
    

    help_FE.py

    def view_formula():
        text1.delete('1.0',END)
        text1.insert(END,help_BE.foo(int(e1.get())))