2011-05-02 6 views
13

저는 Python을 사용하여 프로그래밍 및 GUI 개발에 대한 기초 수업을 가르치고 있으며, 프로그래밍을 처음 접하는 학생들에게 가장 이상적인 해결책은 GUI 개발을 위해 Visual Studio를 사용하는 것입니다.IronPython 및 Visual Studio 2010을 이용한 GUI 개발

C# 및 VB의 GUI 개발 경험은 즐겁지만 IronPython에서도 동일한 작업을 수행 할 수있는 방법을 찾지 못했습니다. Visual Studio 도구가 포함 된 IronPython 2.7.1을 설치하고 WPF IronPython 프로젝트를 만들었습니다.

VB 및 C#과 마찬가지로 WPF 양식 디자이너를 사용할 수 있지만 GUI 요소에 액세스 할 수있는 편리한 방법 (예 : 학생에게 이해하기 쉬운 방법)을 찾을 수 없습니다. 예를 들어 VB에서는 요소의 이름을 기준으로 요소를 참조 할 수 있으며 요소 내의 속성을 수정할 수 있습니다.

import wpf 

from System.Windows import Application, Window 

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

    def Button_Click(self, sender, e): 
     #This is the only way I could find in which I can 
     #access an element and modify its properties 
     self.Content.Children[1].Text += 'Hello World\n' 


if __name__ == '__main__': 
    Application().Run(MyWindow()) 

는 내가하려고 할 때마다 GUI 요소의 이름 및 Visual Studio 충돌하지 않는 것으로 나타났습니다 : 나는 IronPython의 (나는 학생들에게 보여주기 위해 계획하지 않는)와 함께 할 수있는 최선은 다음이다 요소 이름을 지정하기 위해 XAML을 수동으로 수정합니다. 다음은 버튼과 텍스트 영역이있는 간단한 프레임에 대해 생성 된 XAML입니다.

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="WpfApplication3" Height="300" Width="300"> 
    <Grid> 
     <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="103,226,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click" /> 
     <TextBox Height="182" HorizontalAlignment="Left" Margin="24,21,0,0" VerticalAlignment="Top" Width="237" /> 
    </Grid> 
</Window> 

학생들에게이 작업을보다 쉽게 ​​해주는 데 도움이 될만한 정보가 있습니다. 또한 Visual Studio와 유사한 경험을 제공하는 Python GUI 개발에 대한 다른 제안에 대해서도 열려 있습니다.

+1

Qt 디자이너에서 PyQt4를 사용하면 Visual Studio를 사용하는 것보다 훨씬 쉽고 가볍고 간단하다는 것을 알았습니다. Visual Studio를 몇 년 동안 사용해 보았지만 꽤 부 풀었습니다. – Blender

답변

5

IronPython 2.7에서 wpf.LoadComponent 메서드는 모든 속성을 XAML UI 요소와 같은 이름으로 연결합니다. IronPython 2.6을 사용하는 경우 WombatPM에서 제안한 코드를 사용해야합니다. 다음 XAML을 사용하는 경우 그래서 IronPython의 2.7 : 사실

class MyWindow(Window): 
    def __init__(self): 
     wpf.LoadComponent(self, 'IronPyWpf.xaml') 
     self._button.Content = 'My Button' 
     self._textbox.Text = 'My Text' 

    def get_button(self): 
     return self._button 

    def set_button(self, value): 
     self._button = value 

    button = property(get_button, set_button) 

    def get_textbox(self): 
     return self._textbox 

    def set_textbox(self, value): 
     self._textbox = value 

    textbox = property(get_textbox, set_textbox) 

당신이를 단순화 할 수있는 것 같다

<Window 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="IronPyWpf" Height="300" Width="300"> 
    <Grid> 
     <Button x:Name="button" Content="Button" Height="23" HorizontalAlignment="Left" Margin="103,226,0,0" VerticalAlignment="Top" Width="75" /> 
     <TextBox x:Name="textbox" Height="182" HorizontalAlignment="Left" Margin="24,21,0,0" VerticalAlignment="Top" Width="237" /> 
    </Grid> 
</Window> 

그런 다음 당신은 UI 요소에 액세스하는 두 가지 속성을 호출 버튼 및 텍스트 상자를 정의 할 수 있습니다 코드는 더욱 속성 정의 제거하여 : null 참조 예외,

class MyWindow(Window): 
    def __init__(self): 
     wpf.LoadComponent(self, 'IronPyWpf.xaml') 
     self.button.Content = 'My Button' 
     self.textbox.Text = 'My Text' 

불행하게도 Visual Studio를 이미 보았 듯이, 충돌 것 같다 당신은 t하려고 할 때 o XAML을 편집하고 UI 요소에 이름을 지정합니다.

+0

이 답변은 정확합니다. 충돌은 버그처럼 들리며 Visual Studio 용 Python Tools (pythontools.codeplex.com)에서 해결할 수있어서 기쁩니다. http://pytools.codeplex.com/workitem/158에 대한 버그를 열었습니다. 거기서 수정하거나 다시 작성하지 않을 것입니다. 일반적으로 필자는 IronPython 2.7이 내장 된 도구 대신 PTVS를 사용하도록 권장합니다.이 도구는이 시점에서보다 적극적으로 관리되므로 (일반적으로 버그를 꽤 빨리 수정하여 말합니다). –

+0

PTVS가있는 문제를 재현 할 수 없어서 수정되었으므로 (또는 이름을 변경하기 위해 정확히 무엇을하는지에 대한 자세한 정보가 필요함 - 이름, 이름 및 수정을 통해 이름을 변경 함) UI).하나의 가능성은 IpyTools의 오래된 버전입니다. 나중에 버그가 수정 된 버그가 있습니다. –

+0

이 문제는 IronPython 2.7 설치 관리자와 함께 제공되는 Visual Studio Tools에서 x : Name 특성의 이름을 입력 할 때만 발생합니다. 파이썬 도구는 괜찮습니다. 파이썬 도구에서 내가 가진 유일한 문제는 WPF 응용 프로그램을 실행할 수 없다는 것입니다. wpf 라이브러리를 가져 오지 못하는 것 같습니다. –

0

다음과 같은 기능을 사용하여 모든 개체를 탐색하고 더 쉽고 이해할 수있는 참조를 만들어야합니다.

# 
# Waddle returns a dictionary of Control types e.g. listbox, Button. 
# Each Entry is a dictionary of Control Instance Names i.e. 
# controls['Button']['NewSite'] returns the button control named NewSite 
# Controls should have Unique names and only those with a Name attrib set 
# will be included. 
# 
def Waddle(c, d): 
    s = str(c.__class__) 
    if "System.Windows.Controls." in str(c) and hasattr(c,"Name") and c.Name.Length>0: 
     ControlType = s[s.find("'")+1:s.rfind("'")] 
     if ControlType not in d: 
      d[ControlType] = {} 
     d[ControlType][c.Name] = c 
    if hasattr(c,"Children"): 
     for cc in c.Children: 
      Waddle(cc, d) 
    elif hasattr(c,"Child"): 
     Waddle(c.Child, d) 
    elif hasattr(c,"Content"): 
     Waddle(c.Content, d) 
if __name__ == "__main__": 
    xr = XmlReader.Create(StringReader(xaml)) 
    win = XamlReader.Load(xr) 

    controls = {} 
    Waddle(win, controls) 

    #Make all Named buttons do something! 
    for butt in controls['Button']: 
     controls['Button'][butt].Click += sayhello 

    #Make one button do something. 
    controls['Button']['NewSite'].Click += sayhello2 
    Application().Run(win) 

은 위의 코드와 완전한 예를 들어 http://www.ironpython.info/index.php/XAML_GUI_Events_Example 참조하십시오.

관련 문제