Search code examples
pythontkinterscreenshotpyautogui

String data reset after gathering value


I'm trying to save a screenshot file with a name that is introduced by the user, but when it reaches screenshot save command it is reset to first value set at program initialization.

I've set some print functions to debug program however I only discover that is resetting the variable, but not sure why, I made an arrange that is working, but I'm sure it isn't best way to do it.

import pyautogui
import time
from tkinter import *
Serial = "String"
im1 = pyautogui.screenshot

window = Tk() 
window.title("Escanea número de serie")

window.geometry('300x40')
lbl = Label(window, text="Motor:",font=("Arial Bold", 20))
lbl.grid(column=0, row=0)
TextBox1 = Entry(window,width=12)
TextBox1.grid(column=1, row=0)
def clicked():
    Serial = str(TextBox1.get())
    print (Serial) #Until value is the one set by the user
    window.destroy()
    time.sleep(2)
    #im2 = pyautogui.screenshot(Serial + ".png") | Here it works
    #Agregar que hace click
btn = Button(window, text="Guardar",bg="orange", fg="black",command=clicked)    
btn.grid(column=2, row=0)
window.mainloop()
print (Serial) #Here it gets reset to "String" value
im2 = pyautogui.screenshot(Serial + ".png") #Here won't work

It's necessary to retain value for future programs. Any help will be appreciated, Thank you.

Program ask user for data:
enter image description here

If user press button it should start saving screenshot file with value introduced, however it saves it with "String" name.

Result:
enter image description here


Solution

  • To solve your issue, you need to add one line in your function clicked to use global variable Serial and not create a local variable Serial in that function.

    def clicked():
        global Serial
        Serial = str(TextBox1.get())
        print (Serial) #Until value is the one set by the user
        window.destroy()
        time.sleep(2)