Run OpenGL window besides Tkinter window - python-3.x

I am trying to open :
on one hand, an OpenGL window, using glfw
on the other hand, a GUI window, using tkinter
However, both are run with a blocking call for them to render:
glfw: while not glfw.window_should_close(window): ...
Tkinter: self.ui_root.mainloop()
Would you know a way to circumvent that, and to allow to have both windows open at the same time, accepting Keyboard/Mouse events?

If you want to run the tkinter window on a keyboard event, you have to write a callback function to do this. Suppose, if you press "T" then the tkinter window will be showed up. According to your question it will run self.ui_root.mainloop(). Here, the basic structure of your code will be this:
#callback function
def key_input_callback(window, key, scancode, action, mode):
if key == glfw.KEY_T and action == glfw.PRESS:
self.ui_root.mainloop()
#display loop
while not glfw.window_should_close(window):
....
....
glfw.set_key_callback(self.window, key_input_callback)
....
....
Here, the callback function receives the keyboard key and the action, and perform what you want it to do. The action is one of glfw.PRESS, glfw.REPEAT, or glfw.RELEASE.

Related

Control close event pyglet

I have a program that has multiple windows in pyglet, and I want to make one window unclosable, rather to set its visibility to false. Is there a way I can access the event handle for close, to make it instead of closing the window, possibly return a bool or a string like "should close."?
Found the answer to my own question, first define a custom event loop with window_event_loop = pyglet.app.EventLoop(), then create a handler for .event for the event loop
#window_event_loop.event
def on_window_close(window):
# Extra code here
return pyglet.event.EVENT_HANDLED

tkinter button bind() bug

so i wanna bind an enter button to the function so it will work when i press the button with enter button.
but, everytime i do that the button always has a weird bug sometime it always getting in a pressed state or sometime the button act as i write an foregroundonactive parameter in the code.
i always write like this
def itung():
import speedtest
st = speedtest.Speedtest()
lbl['text']=round(st.download/1000000,2)
lbl= Label(root,width=5,height=3)
lbl.place(x=n,y=n)#n here is just an example
btn = Button(root, text='tombol', bg='brown', fg='yellow')
btn.place(x=n,y=n)#n here is just an example
btn.bind('<Return>',itung)
so can someone help me?
You should try this def itung(event = None): in your function. This ensures that the itung receives a None argument as expected, when the key is pressed.
Hi #Dsterror and welcome to the Stack Overflow community! I've seen your question and it seems you just need a little tweak in your code:
#add *args in your parameters for the itung function
def itung(*args):
import speedtest
st = speedtest.Speedtest()
lbl['text']=round(st.download/1000000,2)
lbl= Label(root,width=5,height=3)
lbl.place(x=n,y=n)#n here is just an example
btn = Button(root, text='tombol', bg='brown', fg='yellow')
btn.place(x=n,y=n)#n here is just an example
btn.bind('<Return>',itung)
You can replace the *args with any other parameter variable
Now some explanation.
Whenever you bind a key or a mouse button to a widget, tkinter expects you to create a parameter in the function which gets triggered. You may ask why is this though? What's the relevance? Imagine a left mouse button keybind to the Entry widget. Whenever you click on it, a function should get triggered. Sometimes, we may need the x and y coordinates of the cursor at the time of clicking on the Entry. So tkinter stores this in a list and gives it to the function you're binding to as a parameter. This is why we put in the *args.
Hope you understood something. If not, please tell me the unclear points

PyQt5 UI stuck at long operation

I'm creating a game with some AI that may take some time. The problem is even if I call relevant methods to update the UI before running the AI function, the UI is not visually updated.
Some example code looks like this
def onClickBoard(self, e):
x, y = toBoardGrid(e.x(), e.y())
self.game.move(x, y)
self.update_board()
print("before AI")
# This line takes a few seconds
ai_move = self.ai.get_best_move(self.game)
print("after AI")
self.game.move(ai_move[0], ai_move[1])
self.update_board()
Where self.update_board is a method that updates a QWidget and it's very fast. This onClickBoard method is assigned to the widget's mouseReleaseEvent.
self.board.mouseReleaseEvent = self.onClickBoard
When running the game, I can see before AI printed to the terminal but the visual window doesn't change. I see the window updates only once, after the AI commits its move.
Is there a way to make the board update once before the slow function call and another once after it?
Yes, you can force Qt to process all pending events, and thus update the GUI, with the QApplication::processEvents() method. Add the following line just before the slow function call:
QtWidgets.QApplication.instance().processEvents()

Freeze when using tkinter + pyhook. Two event loops and multithreading

I am writing a tool in python 2.7 registering the amount of times the user pressed a keyboard or mouse button. The amount of clicks will be displayed in a small black box in the top left of the screen. The program registers clicks even when another application is the active one.
It works fine except when I move the mouse over the box. The mouse then freezes for a few seconds after which the program works again. If I then move the mouse over the box a second time, the mouse freezes again, but this time the program crashes.
I have tried commenting out pumpMessages() and then the program works. The problem looks a lot like this question pyhook+tkinter=crash, but no solution was given there.
Other answers has shown that there is a bug with the dll files when using wx and pyhook together in python 2.6. I don't know if that is relevant here.
My own thoughts is that it might have something to do with the two event loops running parallel. I have read that tkinter isn't thread safe, but I can't see how I can make this program run in a single thread since I need to have both pumpmessages() and mainlooop() running.
To sum it up: Why does my program freeze on mouse over?
import pythoncom, pyHook, time, ctypes, sys
from Tkinter import *
from threading import Thread
print 'Welcome to APMtool. To exit the program press delete'
## Creating input hooks
#the function called when a MouseAllButtonsUp event is called
def OnMouseUpEvent(event):
global clicks
clicks+=1
updateCounter()
return True
#the function called when a KeyUp event is called
def OnKeyUpEvent(event):
global clicks
clicks+=1
updateCounter()
if (event.KeyID == 46):
killProgram()
return True
hm = pyHook.HookManager()# create a hook manager
# watch for mouseUp and keyUp events
hm.SubscribeMouseAllButtonsUp(OnMouseUpEvent)
hm.SubscribeKeyUp(OnKeyUpEvent)
clicks = 0
hm.HookMouse()# set the hook
hm.HookKeyboard()
## Creating the window
root = Tk()
label = Label(root,text='something',background='black',foreground='grey')
label.pack(pady=0) #no space around the label
root.wm_attributes("-topmost", 1) #alway the top window
root.overrideredirect(1) #removes the 'Windows 7' box around the label
## starting a new thread to run pumMessages() and mainloop() simultaniusly
def startRootThread():
root.mainloop()
def updateCounter():
label.configure(text=clicks)
def killProgram():
ctypes.windll.user32.PostQuitMessage(0) # stops pumpMessages
root.destroy() #stops the root widget
rootThread.join()
print 'rootThread stopped'
rootThread = Thread(target=startRootThread)
rootThread.start()
pythoncom.PumpMessages() #pump messages is a infinite loop waiting for events
print 'PumpMessages stopped'
I've solved this problem with multiprocessing:
the main process handles the GUI (MainThread) and a thread that consumes messages from the second process
a child process hooks all mouse/keyboard events and pushes them to the main process (via a Queue object)
From the information that Tkinter needs to run in the main thread and not be called outside this thred, I found a solution:
My problem was that both PumpMessages and mainLoop needed to run in the main thread. In order to both receive inputs and show a Tkinter label with the amount of clicks I need to switch between running pumpMessages and briefly running mainLoop to update the display.
To make mainLoop() quit itself I used:
after(100,root.quit()) #root is the name of the Tk()
mainLoop()
so after 100 milliseconds root calls it's quit method and breaks out of its own main loop
To break out of pumpMessages I first found the pointer to the main thread:
mainThreadId = win32api.GetCurrentThreadId()
I then used a new thread that sends the WM_QUIT to the main thread (note PostQuitMessage(0) only works if it is called in the main thread):
win32api.PostThreadMessage(mainThreadId, win32con.WM_QUIT, 0, 0)
It was then possible to create a while loop which changed between pumpMessages and mainLoop, updating the labeltext in between. After the two event loops aren't running simultaneously anymore, I have had no problems:
def startTimerThread():
while True:
win32api.PostThreadMessage(mainThreadId, win32con.WM_QUIT, 0, 0)
time.sleep(1)
mainThreadId = win32api.GetCurrentThreadId()
timerThread = Thread(target=startTimerThread)
timerThread.start()
while programRunning:
label.configure(text=clicks)
root.after(100,root.quit)
root.mainloop()
pythoncom.PumpMessages()
Thank you to Bryan Oakley for information about Tkinter and Boaz Yaniv for providing the information needed to stop pumpMessages() from a subthread
Tkinter isn't designed to be run from any thread other than the main one. It might help to put the GUI in the main thread and put the call to PumpMessages in a separate thread. Though you have to be careful and not call any Tkinter functions from the other thread (except perhaps event_generate).

PyQt save to clipboard in a slot

How can I save some text to clipboard by pressing button? clipboard.setText("gg") works by itself
widget.connect(button, QtCore.SIGNAL('clicked()'), clipboard.setText("text") )
throw error, you can only use instance.methodName
widget.connect(button, QtCore.SIGNAL('clicked()'), clipboard, QtCore.SLOT('setText("text")') )
do nothing.
What is wrong?
First, there's a much better way to connect signals to slots on PyQt:
button.clicked.connect(self.method)
You can use lambda functions to pass extra arguments to methods.
Then you call
button1.clicked.connect(lambda : clipboard.setText('btn one'))
button2.clicked.connect(lambda : clipboard.setText('btn two'))
When you pass a function call, in fact the interpreter is evaluating the call and trying to pass the result to the SIGNAL/SLOT connection. That's why your first example doesn't work.
I've written something similar here: https://stackoverflow.com/questions/...from-other-functions

Resources