如何使用代码在WPF和Python中创建按钮?

0 投票
1 回答
2279 浏览
提问于 2025-04-18 04:25

我需要创建多个按钮,但我一个按钮都显示不出来!这是我用IronPython 2.7写的WPF应用程序的代码。

我尝试了两种不同的方法,一种是用“Grid.Children.Add(button)”,另一种是不使用这个方法,但都没有显示任何东西。

XAML:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Forms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" 
        x:Name="NewWindow" Height="564.22" Width="993.2">

    <Grid x:Name="grid" Margin="0,0,75.2,92.4">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>  
        <Button Content="Create a Button from code" HorizontalAlignment="Left"
         Margin="712,418,0,0" VerticalAlignment="Top" Width="167" Height="61"
         Click="CreateButtons_Click"/>     
    </Grid>
</Window>

代码:

import clr
clr.AddReferenceToFileAndPath("IronPython.Wpf.dll")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("Microsoft.Scripting")

import wpf 
from System.Windows import Application, Window, Controls
from System.Windows.Forms import Form, Button

class NewWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'NewWindow.xaml')

    def CreateButtons_Click(self, sender, e):
        self.myButton = Button()
        self.myButton.Name="boton1"
        self.myButton.Text="prueba"
        self.myButton.Size = Size(75,23)
        self.myButton.Location = Point(0,0)
        #Add to grid
        self.grid.Children.Add(self.myButton)

这段代码报了一个错:

期望是UIElement,结果得到了Button

如果我跳过这个错误,删掉那行self.grid.Children.Add(self.myButton),就不会报错了,但按钮也还是不显示。

我该怎么用Python代码把按钮显示出来呢?(我刚开始学Python和WPF)

1 个回答

0

我找到了问题所在!!(太简单了,我简直不敢相信!)

UIElement的错误是因为(我不知道有两种按钮,真抱歉!)我从System.Windows.Forms导入了Button,但正确的按钮应该从System.Windows.Controls导入。

大家祝你们有个愉快的一天!

撰写回答