StefanGreve
StefanGreve

Reputation: 171

Accessing Children in LabelFrames using Tkinter and Python 3

I am working with tkinter and have set up a bare bones application of my project. My objective is to retrieve a value from tk.Entry() which lies within a tk.LabelFrame() (in this code referenced by the groupbox variable). The button finds the groupbox, and the code passes the compiler, too. I guess my question is: How do I access Widgets and their values in a LabelFrame?

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tkinter as tk


class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master.title("Application Title")

        # Introduce LabelFrame
        self.groupbox = tk.LabelFrame(self, text="Parameters")
        self.groupbox.grid(row=0, column=1, padx=5, pady=5)

        # Test Label & Entry Widget
        label = tk.Label(self.groupbox, text="label=")
        label.grid(row=0, column=0, sticky="W")
        entry = tk.Entry(self.groupbox)
        entry.insert(0, default_value)
        entry.grid(row = 0, column=1)

        # Compile Button
        button = tk.Button(self.groupbox, text="Compile", command=self.compile)
        button.grid(row=1, column=1)

    # Retrieve first Value (second Widget) from LabelFrame
    def compile(self):
        print(self.groupbox.entry.get(1))

if __name__ == '__main__':
    figure = Application()
    figure.pack()
    figure.mainloop()

I am doing this because I want to perform some calculations based on the tk.Entry() values triggered by a button click which is contained in the same LabelFrame() as suggested by the code snippet above (in the original code there are a lot more widgets but that's essentially the gist of my current problem).

Upvotes: 0

Views: 729

Answers (1)

Henry Yik
Henry Yik

Reputation: 22493

Change entry to self.entry.

class Application(tk.Frame):
    def __init__(self, master=None):

        ....
        self.entry = tk.Entry(self.groupbox)
        self.entry.insert(0, "default_value")
        self.entry.grid(row = 0, column=1)
        ...

    # Retrieve first Value (second Widget) from LabelFrame
    def compile(self):
        print(self.entry.get())

Upvotes: 1

Related Questions