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

问题描述

在我提出我的问题之前,我(自我)正在学习 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) # This does not