Python .NET WinForms-如何将信息从文本框传递到按钮单击事件 [英] Python .NET WinForms - How to pass info from a textbox to a button click event
问题描述
在开始讨论问题之前,我(自己)正在学习Python和.NET CLR如何彼此交互.这虽然很有趣,但有时还是令人沮丧的经历.
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.
话虽如此,我正在.NET WinForm上玩,它应该只是简单地传递键入到文本框中的数据并通过消息框显示它们.学习如何做到这一点应该促使我采用其他传递数据的方式.这个简单的任务似乎使我难以捉摸,而且我似乎找不到任何有关tyo如何做到这一点的良好文档.有没有人尝试过?如果是这样,我愿意学习,以便有人能指出正确的方向或提示我做错了什么?
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-我已经在C#.NET和VB.NET中进行了一些编码,因此传递变量似乎应该足够了,但显然不是.
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://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
(指实例本身)上,以使其成为实例变量:
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
和
def buttonPressed(self, sender, args):
MessageBox.Show('This works.')
MessageBox.Show(self.txt.Text) # This does not
这篇关于Python .NET WinForms-如何将信息从文本框传递到按钮单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!