How to exit GUI program by clicking the mouse in Python? - python

from graphics import *
def main():
win = GraphWin("Shapes")
center = Point(100, 100)
circ = Circle(center, 30)
circ.setFill("red")
circ.draw(win)
time.sleep(6)
main()
So, I have installed (barely somehow) graphics.py by John Zelle so I can follow his book (An Introduction to Comp. Sci.) material for Chapter 5 Objects and Graphics.
I am writing all of my code in Sublime Text editor and when I want to compile, I go to cmd and type: python "name_of_file".py and start the program this way.
In this package there is an object Window which is created by invoking GraphWin() (everything will be drawn here in the whole chapter), but that object stays visible for just a split of a second (my guess is because main() is executed and therefore it is done).
On the contrary, if I type all of required code (from that package) in the cmd, that Window object (and everything on it) stays visible the entire time.
It is very inconvenient to type in cmd. Is there something I can type inside main() to keep my work (Window object and everything else) visible, until lets say, I click a mouse or press Enter? I don't know how to implement that in Python.

Use getMouse() method of GraphWin object. It will wait until you click to continue execution.
from graphics import *
def main():
win = GraphWin("Shapes")
center = Point(100, 100)
circ = Circle(center, 30)
circ.setFill("red")
circ.draw(win)
win.getMouse()
main()

Related

Pygame program keeps crashing and the display window won't cooperate,

Trying to design and call open a basic customized pygame window that pops up right after the program starts. The window I'm producing gets minimized by default instead of just opening. It's also not updating the color, and it immediately crashes when I open the tab that it's in.
# I'm running Windows 10 with Spyder (Python 3.9), if that matters
# This is the entire code:
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter Friends (Version 1.0)")
# Color presets
WHITE = (255,255,255)
BLACK = (0,0,0)
# Event loop
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
WIN.fill(WHITE)
pygame.display.update()
pygame.quit()
# Ensure the game only executes in the file named: space_shooter.py
if __name__ == "__space_shooter__":
main()
For context, I'm a beginner level student just trying to generate a basic white display for now, with dimensions: 9ooW x 500H, and centered ideally so that the pygame window's center is superimposed onto the center of my computer screen. I want this window to pop up as soon as the program starts running, and it should stay open for an indefinite amount of time, or until exited from with the X icon.
It seems to be producing the window right away as intended, but it places it into a minimized tab instead of an opened window display for some reason. The window pops open if I click on the tab, but it's filled in with black regardless of what values I insert into WIN.fill(R,B,G) as arguments. Also, the program immediately becomes non-responsive with the message: (Not responding) next to the game's title (at the top of the pygame window, not in the Spyder terminal).
Seems like it's not able to update for some reason, possibly causing it to crash, but I'm not really sure. I'm not getting any runtime or syntax errors from Python, but I do get a "Python is not responding" message from Windows in the pygame window as well as whenever I try to close the window using the X icon. Any help is much appreciated!
The problem is in the following line:
if __name__ == "__space_shooter__":
The __name__ variable will not contain the file name of the current script. If the script is ran directly, it will contain "__main__". If the script is imported by another script, it will contain the file name of that other script.
In order to check the script's file name, which you according to the comment wanted to do, you have to use the __file__ variable. The only problem is that the __file__ variable does not only containt the file name, but also the file path and the file extension. That's why I would use the str.endswith function, which checks whether a certain string ends with a given string. There are also some more complicate and reliable ways, but I will leave it to this:
if __file__.endswith("space_shooter.py"):
However, it is more common to check whether the current file is being ran directly instead of being imported from another file. This allows other files to import and use the functions and classes present in the file, without that everything in the file is ran too.
For this, you have to use the __name__ variable:
if __name__ == "__main__":
As said above, the __name__ variable will contain "__main__" when the file is ran directly. Thus we can compare __name__ with it to know whether the file is ran directly or not.
For more information on the __name__ variable, there is more explanation and a useful example.

pyautogui and pydirectinput not working properly on Halo 5?

I am trying to write a script in python that would take control of Halo 5 forge in order to automatically create and script an in-game script brain object and use the game's built-in scripting system to script the object to randomize the movement of 2 agents (will be added later) in order to procedurally generate a map, saving me time in doing tedious manual work on creating a method from scratch I have repeated many times in Halo 5 Forge.
Basically I am trying to create a class representing this script brain object in python and under the init method it is supposed to follow all of the steps in Forge to create a script brain object.
At first I tried pyautogui as it initially worked previously on Halo 5. But now it doesn't seem to work. It is a known issue that pyautogui doesn't input certain things properly on directX games and was suggested pydirectinput as an alternative.
So I did and while the mouse responds properly in the game and opens the object menu using the press() method, it doesn't actually seem to respond to leftClick() for some reason, only repositioning the mouse to the correct position but not actually clicking the object menu like I had hoped.
Here is the code:
import os
import pyautogui as pygui
import pydirectinput as pydi
import time
class forgeObjectRandomizer:
def __init__(self):
#CREATE THE SCRIPT BRAIN
time.sleep(5)
screenWidth, screenHeight = pydi.size()
pydi.moveTo(round(screenWidth / 2), round(screenHeight / 2))
time.sleep(1)
# pydi.leftClick(1749, 44)
pydi.press('o')
time.sleep(0.5)
pydi.leftClick(1554, 337) # --- Extras
time.sleep(0.5)
pydi.leftClick(1605, 266) # --- Scripting
time.sleep(0.5)
pydi.leftClick(1630, 236) # --- Script Brain
time.sleep(0.5)
pydi.press('p') # --- Properties
time.sleep(0.5)
pydi.mouseDown(1886, 231) # --- Scroll down
pydi.moveTo(1886, 453) # --- Scroll down
pydi.mouseUp()
brainRandomizer = forgeObjectRandomizer()
You can use to move mouse
import win32api,win32con
def click():
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, int(x), int(y), 15, 15)
for mouse click equivalent, but I only had problems with moving the mouse
This is kinda a blind shot since u said pyautogui was working fine before on halo 5...are you running the game as administrator? If so make sure that ur code does too, because i had same problem in a game named asda global

PyCharm closes external GraphWin window immediately

Following a beginners Python3 tutorial, I am supposed use the graphics module to generate an external GraphWin() window and keep it until win.close() is initiated.
At the moment I don't wish to run win.close() and want to keep it open, but PyCharm's "process finished with exit code 0" shuts it off automatically. How can i solve this?
thank you in advance!!
The Overview at the very beginning of the Zelle graphics documentation explains this:
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # pause for click in window
win.close()
main()
It's the combination of:
win.getMouse() # pause for click in window
win.close()
That holds the window open until the the user clicks on it. Primitive but effective. I checked and it seems to work fine with PyCharm.

graphics.py GraphWin automatically closing

I'm new to Python and trying to learn graphics with John Zelle's graphics.py. I'm writing the Python scripts in MacVim and executing from the terminal (Mac OS 10.9.2) on Python 3. If I try to open a new window with GraphWin() the window opens briefly but then immediately closes.
Ex:
from graphics import *
win = GraphWin("circle",500,500)
c = Circle(point(100,100),30)
c.draw(win)
GUI elements with TkInter work just fine.
Any ideas why this might be happening?
Thanks!
If the statements you've shown in your question were entered as a script, and you just ran the script, then the problem is that the window is closed implicitly when the script ends. You will see in the very first example from the documentation (which also appears in the source code for graphics.py itself):
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # Pause to view result
win.close()
main()
Notice that the author has specifically included a statement to pause before closing the window.
If, instead of a script, you just type the statements in one by one at an interactive Python prompt, then as long as that Python prompt is open, the graphics window stays open (until you explicitly close it, or close the Python session).

Python crashing on Mac

I just download a graphics module (found at http://mcsp.wartburg.edu/zelle/python/) and wrote a quick program to test it out. All it is supposed to do is create a window. It works, but the second the window is created Python (not IDLE) goes non-responsive and I have to force quit. What could be causing this? The code (that they provide as an example) is:
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse()
win.close()
After I click it suddenly crashes.
This is actually expected behavior. The line
win.getMouse()
hangs the interpreter and window until you click. After the click, the line
win.close()
destroys the window, then your program terminates. This may appear as a "crash" to you, but is actually the expected end of your Python program's run. (If you're getting an error, post the trace in your question.)

Categories

Resources