我以前在研究IronPython(使用WPF开发一些gui),最近我开始尝试pythonnet。你知道吗
但是我发现在IronPython上工作的xaml文件在CPython+pythonnet上不工作。在IronPython中,我可以定义按钮。单击在xaml文件中,但在CPython中似乎不可能。我试图寻找答案,但没有找到相关的。所以希望你能救我。。。你知道吗
以下是我的主要剧本:
import clr
clr.AddReference(r"wpf\PresentationFramework")
from System.IO import StreamReader
from System.Windows.Markup import XamlReader
from System.Windows import Application, Window
from System.Threading import Thread, ThreadStart, ApartmentState
class MyWindow(Window):
def __init__(self):
stream = StreamReader('test.xaml')
window = XamlReader.Load(stream.BaseStream)
Application().Run(window)
def Button_Click(self, sender, e):
print('Button has clicked')
if __name__ == '__main__':
thread = Thread(ThreadStart(MyWindow))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
这里是测试.xmal地址:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WpfApplication1" Height="300" Width="300">
<Grid>
<Button x:Name="BUTTON" Content="Button" HorizontalAlignment="Left" Margin="101,82,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click" Background="#FFFF1616"/>
</Grid>
</Window>
我得到的错误信息是:
未处理的异常:Python.Runtime.PythonException异常:XamlParseException:'无法从文本“Button\u Click.”创建“Click”。'行号“6”和行位置“132”。
如果我加载相同的xaml并在IronPython中保持相同的类结构,那么脚本就可以正常工作:
import wpf
from System.Windows import Application, Window
class MyWindow(Window):
def __init__(self):
self.ui = wpf.LoadComponent(self, 'test.xaml')
def Button_Click(self, sender, e):
print('Button has clicked')
if __name__ == '__main__':
Application().Run(MyWindow())
非常感谢你的帮助!你知道吗
不能使用pythonnet包在python中导入wpf。但是您可以在PresentationFramework中使用PresentationFramework加载XAML文件,这有一些限制。XamlReader无法执行事件处理,因此我们可以在python文件中手动添加该按钮的事件,而不是在XAML文件中。你知道吗
听到了吗图形用户界面.xaml代码
然后听python代码
相关问题 更多 >
编程相关推荐