Skip to content
Advertisement

Python .NET WinForms – How to pass info from a textbox to a button click event

Before I get into my question, I am (self) learning how Python and the .NET CLR interact with each other. It has been a fun, yet, at times, a frustrating experience.

With that said, I am playing around on a .NET WinForm that should just simply pass data that is typed into a text box and display it via a message box. Learning how to do this should propel me into other means of passing data. This simple task seems to elude me and I can’t seem to find any good documentation on how tyo accomplish this. Has anyone attempted this? If so, I am willing to learn so if someone could point me in the right direction or give me a hint as to what I’ve done wrong?

PS – I have done some coding in C#.NET and VB.NET so the passing of the variables seems like it should be enough but apparently it isn’t.

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")

from System.Windows.Forms import *
from System.Drawing import *

class MyForm(Form):
    def __init__(self):

        # Setup the form
        self.Text = "Test Form"
        self.StartPosition = FormStartPosition.CenterScreen # https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.startposition?view=net-5.0

        # Create label(s)
        lbl = Label()
        lbl.Parent = self
        lbl.Location = Point(15,15) # From Left, From Top
        lbl.Text = "Enter text below"
        lbl.Size =  Size(lbl.PreferredWidth, lbl.PreferredHeight)

        # Create textbox(s)
        txt = TextBox()
        txt.Parent = self
        txt.Location =  Point(lbl.Left - 1, lbl.Bottom  + 2) # From Left, From Top

        # Create button(s)
        btn = Button()
        btn.Parent = self
        btn.Location =  Point(txt.Left - 1, txt.Bottom + 2) # From Left, From Top
        btn.Text = "Click Me!"

        btn.Click += self.buttonPressed

    def buttonPressed(self, sender, args):
        MessageBox.Show('This works.')
        MessageBox.Show(txt.Text) # This does not

Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)

form = MyForm()
Application.Run(form)

Advertisement

Answer

txt is a local variable in __init__, meaning that you can’t access it from any other function. To fix it, make it an instance variable by attaching it to self (which refers to the instance itself):

self.txt = TextBox()
self.txt.Parent = self
self.txt.Location =  Point(lbl.Left - 1, lbl.Bottom  + 2) # From Left, From Top

and

def buttonPressed(self, sender, args):
    MessageBox.Show('This works.')
    MessageBox.Show(self.txt.Text) # Now this does too
Advertisement