Python .NET WinForms - 如何将信息从文本框传递到按钮单击事件

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

在开始我的问题之前,我正在(自我)学习 Python 和 .NET CLR 如何相互交互。这是一次有趣但有时令人沮丧的经历。

话虽如此,我正在玩 .NET WinForm,它应该只是简单地将键入的数据传递到文本框中并通过消息框显示它。学习如何做到这一点应该会促使我采用其他方式传递数据。这个简单的任务似乎让我望而却步,而且我似乎找不到任何关于您如何完成此任务的好文档。有没有人尝试过这个?如果是这样,我愿意学习,如果有人能指出我正确的方向或给我提示我做错了什么?

PS - 我在 C#.NET 和 VB.NET 中完成了一些编码,因此传递变量似乎应该足够了,但显然还不够。

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://docs.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)

txt__init__ 中的局部变量,这意味着您无法从任何其他函数访问它。要修复它,通过将其附加到 self(指的是实例本身)使其成为一个实例变量:

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

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