Home > Enterprise >  Tkinter and pulling a textbox value on button press
Tkinter and pulling a textbox value on button press

Time:08-31

I used Visual TK as a generator for GUI for my app, but i have a problem. I want to pull the textbox values from one function into the button function. Also I want to update a label from within the button function also. I can't seem to do it because they are not defined.

The problem is in these two lines: number = self.PoleMaticen.get("1.0", "end") and GLabel_250["text"] = number

class App:
    def __init__(self, root):
        #setting title
        root.title("Some title")
        #setting window size
        width=272
        height=297
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d %d %d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        PoleMaticen=tk.Entry(root)
        PoleMaticen["borderwidth"] = "1px"
        ft = tkFont.Font(family='Arial',size=10)
        PoleMaticen["font"] = ft
        PoleMaticen["fg"] = "#333333"
        PoleMaticen["justify"] = "left"
        PoleMaticen["text"] = "INPUT THE NUMBER"
        PoleMaticen.place(x=110,y=10,width=139,height=30)
        PoleMaticen.focus()

        GLabel_250=tk.Label(root)
        GLabel_250["anchor"] = "ne"
        ft = tkFont.Font(family='Arial',size=10)
        GLabel_250["font"] = ft
        GLabel_250["fg"] = "#333333"
        GLabel_250["justify"] = "left"
        GLabel_250["text"] = "The number"
        GLabel_250.place(x=10,y=10,width=87,height=30)
        
        GButton_baraj=tk.Button(root)
        GButton_baraj["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Arial',size=10)
        GButton_baraj["font"] = ft
        GButton_baraj["fg"] = "#000000"
        GButton_baraj["justify"] = "center"
        GButton_baraj["text"] = "Lookup"
        GButton_baraj.place(x=20,y=90,width=227,height=30)
        GButton_baraj["command"] = self.GButton_baraj_command

    def GButton_baraj_command(self):
        wb = openpyxl.load_workbook("workbook.xlsx")
        ws = wb.active
        number = self.PoleMaticen.get("1.0", "end")
        GLabel_250["text"] = number
        



if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

CodePudding user response:

PoleMaticen and GLabel_250 are variables local to __init__, which is why trying to use them in another function understandably fails.

If you need to use them as self.PoleMaticen and self.GLabel_250, assign them to those fields on self:

PoleMaticen = tk.Entry(root)
# ...
self.PoleMaticen = PoleMaticen

etc.

  • Related