New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
The calling thread must be STA #990
Comments
What you need is a single apartment thread for COM. You can do it either by manually calling https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-coinitializeex or start a separate thread using .NET: https://stackoverflow.com/questions/11681666/starting-an-stathread-in-c-sharp |
@jz499 I got more questions in email, but I don't see them in this thread. Have you been able to get it working? Should we close the topic? |
Hi @lostmsu , I got it partially working. I created an apartment thread in Python, the code executes with no errors, but it does not display the window or controls. Here's the threading I added to the above code.
|
@jz499 I think that happens, because Python can only execute 1 thread at time. E.g. while main Python interpreter is busy in Probably you need to call |
Hi @lostmsu, stream = StreamReader("my_app.xaml") |
Environment
Details
Hi Everyone;
I'm trying to run a basic wpf application from within Python using VS code. When the script executes I get the error listed at the bottom of this page. Has anyone seen this error before?
My Code:
import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")
from System.Windows import (Application, SizeToContent, Thickness, Window)
from System.Windows.Controls import (Button, Label, StackPanel)
from System.Windows.Media.Effects import DropShadowBitmapEffect
window = Window()
window.Title = 'Welcome'
window.SizeToContent = SizeToContent.Height
window.Width = 450
stack = StackPanel()
stack.Margin = Thickness(15)
window.Content = stack
button = Button()
button.Content = 'Button1'
button.FontSize = 24
button.BitmapEffect = DropShadowBitmapEffect()
def onClick(sender, event):
message = Label()
message.FontSize = 36
message.Content = 'Welcome'
stack.Children.Add(message)
button.Click += onClick
stack.Children.Add(button)
app = Application()
app.Run(window)
Error Output:
File "c:/Users/WIN-VMMV970AOGL/pyfolder/test.py", line 10, in
window = Window()
System.InvalidOperationException: The calling thread must be STA, because many UI components require this.
at System.Windows.Input.InputManager..ctor()
at System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
at System.Windows.Input.KeyboardNavigation..ctor()
at System.Windows.FrameworkElement.FrameworkServices..ctor()
at System.Windows.FrameworkElement.EnsureFrameworkServices()
at System.Windows.FrameworkElement..ctor()
at System.Windows.Controls.Control..ctor()
at System.Windows.Window..ctor()
The text was updated successfully, but these errors were encountered: