env:python37,windows,wxpython
在应用程序运行时有一个主框架保持打开状态,现在我正尝试在鼠标右键单击上创建一个新框架,如果我通过单击按钮打开它,但是如果它是由鼠标触发的,则该新框架会很好地工作click事件,它将挂起并且没有响应。我在想鼠标侦听器是否有问题,如果您有任何想法,请多谢。
这是代码详细信息:
import wx
import time
import win32api
from threading import Thread
class OtherFrame(wx.Frame):
"""
Class used for creating frames other than the main one
"""
def __init__(self, title, parent=None):
wx.Frame.__init__(self, parent=parent, title=title)
panel = wx.Panel(self)
panel.SetBackgroundColour('yellow')
self.Show()
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
btn = wx.Button(self, label='Create New Frame')
btn.Bind(wx.EVT_BUTTON, self.on_new_frame)
self.frame_number = 1
thread = Thread(target=self.monitorMouse, name='monitorMouse')
thread.daemon = True
thread.start()
def monitorMouse(self):
state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128
state_right = win32api.GetKeyState(0x02) # Right button down = 0 or 1. Button up = -127 or -128
while True:
a = win32api.GetKeyState(0x01)
b = win32api.GetKeyState(0x02)
if b != state_right: # Button state changed
state_right = b
if b < 0:
print('Right Button Pressed')
else:
print('Right Button Released')
self.on_new_frame(None)
time.sleep(0.001)
def on_new_frame(self, event):
title = 'SubFrame {}'.format(self.frame_number)
frame = OtherFrame(title=title)
self.frame_number += 1
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Main Frame', size=(800, 600))
panel = MyPanel(self)
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MainFrame()
app.MainLoop()
答案 0 :(得分:0)
如果确定要使用线程监视鼠标,那么我认为您将不得不看看wx.lib.newevent.NewEvent()
。
在线程中,您将使用wx.PostEvent
将鼠标事件发送回主程序。
但是,wxpython
已经为您提供了鼠标事件,您可以直接将其绑定到例如
import wx
class OtherFrame(wx.Frame):
def __init__(self, title, parent=None):
wx.Frame.__init__(self, parent=parent, title=title)
panel = wx.Panel(self)
panel.SetBackgroundColour('yellow')
self.Show()
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
btn = wx.Button(self, label='Create New Frame')
btn.Bind(wx.EVT_BUTTON, self.on_new_frame)
self.Bind(wx.EVT_LEFT_DOWN, self.Left)
self.Bind(wx.EVT_RIGHT_DOWN, self.Right)
self.Bind(wx.EVT_RIGHT_DCLICK, self.on_new_frame)
self.Bind(wx.EVT_CLOSE, self.Quit)
self.frame_number = 1
def Quit(self, event):
self.Destroy()
def Left(self, event):
print("Left Button")
event.Skip()
def Right(self, event):
print("Right Button")
def on_new_frame(self, event):
title = 'SubFrame {}'.format(self.frame_number)
frame = OtherFrame(parent=self,title=title)
self.frame_number += 1
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Main Frame', size=(800, 600))
panel = MyPanel(self)
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MainFrame()
app.MainLoop()
顺便说一句,注意这行
frame = OtherFrame(parent=self,title=title)
发送parent
可以在关闭主框架时关闭所有未完成的OtherFrame's
。