因此,我使用C#在Visual Studio中制作了Winforms GUI,但对于我正在从事的项目,我希望大多数代码都用Python编写.我希望用python编写“引擎”(出于可移植性),然后使应用程序接口成为我可以交换的东西.
我将C#项目编译为.dll,并且能够将这些类导入IronPython脚本并正常启动GUI.
问题是运行GUI会停止执行Python脚本,除非我将其放到单独的线程中.但是,如果我将GUI放在单独的线程中,并尝试使用原始的python线程来更改状态信息,则在从不同于创建该线程的线程中修改控件时,会出现异常.
有没有什么好的方法可以与GUI线程通信,或者可以完成我想做的事情?
GUI的C#驱动程序:
public class Program
{
private static MainWindow window;
[STAThread]
static void Main()
{
Program.RunGUI();
}
public static void RunGUI()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
window = new MainWindow();
Application.Run(window);
}
public static void SetState(GameState state)
{
window.State = state;
}
}
和python脚本:
import clr
clr.AddReferenceToFile("TG.Model.dll")
clr.AddReferenceToFile("TG.UI.dll")
from TG.Model import GameState
from TG.UI import Program
import thread
import time
def main():
print "Hello!"
state = GameState()
print state.CharacterName
print dir(Program)
thread.start_new_thread(Program.RunGUI, ())
#Program.RunGUI()
time.sleep(2)
Program.SetState(state)
raw_input()
if __name__ == "__main__":
main()
解决方法:
将所有内容放在对事件的Program.RunGUI()调用之后.
C#:
public static void RunGUI(EventHandler onl oad)
{
...
window = new MainWindow();
window.Load += onl oad;
Application.Run(window);
window.Load -= onl oad; //removes handler in case RunGUI() is called again
}
Python:
def onl oad(sender, args):
time.sleep(2)
Program.SetState(state)
raw_input()
def main():
...
Program.RunGUI(onload)