So I made a Winforms GUI in Visual Studio using C#, but for the project I am working on I want the majority of the code to be written in Python. I am hoping to have the "engine" written in python (for portability), and then have the application interface be something I can swap out.
I made the C# project compile to a .dll, and was able to import the classes into an IronPython script and start the GUI fine.
The problem is that running the GUI stops the execution of the Python script unless I put it into a separate thread. However, if I put the GUI into a separate thread and try and use the original python thread to change state information, I get an exception about modifying a control from a different thread than what created it.
Is there any good way to communicate with the GUI thread or a way to accomplish what I am trying to do?
The C# driver of the GUI:
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;
}
}
And the python script:
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()
Put everything after the call to Program.RunGUI() in an event handler.
C#:
public static void RunGUI(EventHandler onLoad)
{
...
window = new MainWindow();
window.Load += onLoad;
Application.Run(window);
window.Load -= onLoad; //removes handler in case RunGUI() is called again
}
Python:
def onload(sender, args):
time.sleep(2)
Program.SetState(state)
raw_input()
def main():
...
Program.RunGUI(onload)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With