In turtle, I am interested in finding out the canvas dimensions once my main window has "maximized".
The code for creating and maximizing a turtle window is:
def make_window2():
canvas = t.getcanvas()
root = canvas.winfo_toplevel()
root.title("Serpenski")
root.state('zoomed')
return root, canvas, t
where t is the imported turtle object (i.e import turtle as t)
Issue happens when I try to use it.
window, canvas, turtle = make_window2()
screen = turtle.Screen()
win_width = screen.window_width()
win_height = screen.window_height()
print((win_width, win_height))
time.sleep(10) #waiting 10 seconds
win_width = screen.window_width()
win_height = screen.window_height()
print((win_width, win_height)) # Prints the same thing as before...
I ran my script in the interpreter mode (passing -i switch to python binary). During time.sleep(10), if you happen to see turtle window, you'd see that the resize operation is in progress and it hangs until the next interpreter prompt is shown (i.e. when the above bit of code completes executing). Please note, that the resize operation completes after this code execution is over.
So how to run the above code after the root window has maximized?
PS: using python 3.10.2, on windows 11 machine.
Not sure if it is a soluiton. After some hacking around, I found that turtle.reset() does the trick.
Related
I need the window position right after I created a pygame window:
window = pygame.display.set_mode((width, height), 0, 32)
pygame.init()
By default, the window starts at 0,0 - but I also need x,y if the user changes the window position. Any ideas?
I need x,y coords of the pygame window - either at start or on window move. The last one is nice to have.
I figured out how to center the pygame window at the bottom of the screen:
pos_x = screen_width / 2 - window_width / 2
pos_y = screen_height - window_height
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y)
os.environ['SDL_VIDEO_CENTERED'] = '0'
Background: I have x,y coords which are screen related and I must convert the screen coords into window-local coords so that I can use them e.g. to display coords inside the pygame window or to discard coords which are outside the pygame window.
With my approach above, I knwo the initial position. But I can only use a single pygame window (because it's always at the same position) and things go wrong if the user moves the window.
It have worked for me :
import os
import pygame
x = 100
y = 45
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
pygame.init()
screen = pygame.display.set_mode((100,100))
Taken from https://www.pygame.org/wiki/SettingWindowPosition
Here is an example code that return all four corner positions:
from ctypes import POINTER, WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HWND, RECT
# get our window ID:
hwnd = pygame.display.get_wm_info()["window"]
# Jump through all the ctypes hoops:
prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
paramflags = (1, "hwnd"), (2, "lprect")
GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
# finally get our data!
rect = GetWindowRect(hwnd)
print "top, left, bottom, right: ", rect.top, rect.left, rect.bottom, rect.right
# bottom, top, left, right: 644 98 124 644
There is a pygame.display.get_wm_info() call that gets you the Window handler -- from then on, it is using either X11 or Windows API32 to get information from the window through this handler. I didn't find any readily available information on how to do that.
So, just to be clear: there is no ordinary way to do that from within pygame. You have to proceed with another library, possibly using ctypes, after you get the window handler.
On the other hand, if you have to manipulate the window itself, maybe pygame is not the most suitable library for you to use -- you could try PyQt or even GTK+ - they also provide multmedia facilites while being more proper to operate on the level of GUI Windows and other controls
update There are ways to setup an OpenGL backend for pygame graphics, that will allow complete control of the display - including embedding it in another window, as part of a tkinter or Qt application. People that are interested can search a little deeper along those lines.
In Pygame 2, you can alternatively import the _sdl2.video to set the window position. Note that this module is experimental and could be changed in future versions.
import pygame
from pygame._sdl2.video import Window
pygame.init()
window = Window.from_display_module()
window.position = your_position_tuple
Using environment variables as mentioned in other answers is sufficient for most cases, but the downside is that once you have change the window position it will not work a second time (at least in Pygame 2).
Pygame is based on Simple DirectMedia Layer (SDL). Hence you can set SDL environment variables.
See pygame wiki - SettingWindowPosition:
You can set the position of the window by using SDL environment variables before you initialise pygame. Environment variables can be set with the os.environ dict in python.
x = 100
y = 0
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
import pygame
pygame.init()
screen = pygame.display.set_mode((100,100))
(0,0) remains the upper left corner whether the window is moved or not. If you're trying to make (0,0) stay physically where it was on the screen when the window initialized, I don't think pygame can do that. Try to make your question clearer if you want clearer answers.
To accomplish this where you don't know the monitor size of the user, use screeninfo in addition to the pygame and os packages. Screeninfo is OS-agnostic, meaning you can get the resolution of all monitors regardless of a users operating system.
import pygame
from screeninfo import get_monitors
import os
# Set the size of the pygame window
window_width = 512
window_height = 288
window_size = (window_width, window_height)
# Get the bounds of the users monitors, and select the first one
monitors = get_monitors() # Get the resolution of all of the users monitors
screen_width = monitors[0].width # Get width of first monitor found
screen_height = monitors[0].height # Get height of first monitor found
# Set the x and y coordinates of the pygame window in relation to the monitor's resolution
# (I wanted my pygame window to be located in the bottom-right of the monitor)
pos_x = screen_width - window_width # Calculate the x-location
pos_y = screen_height - window_height # Calculate the y-location
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y) # Set pygame window location
pygame.init() # Initialize the pygame window
self.screen = pygame.display.set_mode(size) # Set the location of the pygame window
I've been testing the turtle library for about 3 days now. One recurring 'issue' that I've been getting is the traceback error whenever I exit my application window. The terminal displays rows of details regarding the turtle update function and it ends with:
_tkinter.TclError: can't invoke "update" command: application has been destroyed
Here's my code:
import turtle
wn = turtle.Screen()
wn.title("Game Window")
wn.bgcolor("black")
wn.setup(width=1000, height=650)
wn.tracer(0)
run = True
while run:
wn.update()
I've been trying to wrap my head around the traceback report. I'm assuming it happens because the application continuously updates the window (as you can see in the while run block). So, there is a possibility that, once I exit the window, the application is already processing the wn.update() function, and it returns an error because it did not finish its operation. If that is the case, then what should I do about the update function? If not then, please, explain to me the issue and solution. Thank you!
The problem is your loop:
while run:
wn.update()
This is the wrong way to approach Python turtle programming. I see this loop often in SO questions so there must be a book ("Programming Python Turtle by Bad Example") or tutorial somewhere teaching people the wrong way to approach turtle.
Generally, I'd suggest you avoid tracer() and update() until your program is basically working and you now need to optimize its performance. If you do use tracer(), then you should only call update() when you are finished making changes and you want the user to see the current display. Something like:
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width=1000, height=650)
screen.title("Game Window")
screen.tracer(0)
turtle = Turtle()
radius = 1
while radius < 300:
turtle.circle(radius, extent=1)
radius += 0.25
screen.update() # force above to be seen
screen.mainloop()
A key point to note is that our program ends with a mainloop() call which passes control onto Tk(inter)'s event loop. That's the same event loop that receives the window close event and closes down turtle cleanly.
I need the window position right after I created a pygame window:
window = pygame.display.set_mode((width, height), 0, 32)
pygame.init()
By default, the window starts at 0,0 - but I also need x,y if the user changes the window position. Any ideas?
I need x,y coords of the pygame window - either at start or on window move. The last one is nice to have.
I figured out how to center the pygame window at the bottom of the screen:
pos_x = screen_width / 2 - window_width / 2
pos_y = screen_height - window_height
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y)
os.environ['SDL_VIDEO_CENTERED'] = '0'
Background: I have x,y coords which are screen related and I must convert the screen coords into window-local coords so that I can use them e.g. to display coords inside the pygame window or to discard coords which are outside the pygame window.
With my approach above, I knwo the initial position. But I can only use a single pygame window (because it's always at the same position) and things go wrong if the user moves the window.
It have worked for me :
import os
import pygame
x = 100
y = 45
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
pygame.init()
screen = pygame.display.set_mode((100,100))
Taken from https://www.pygame.org/wiki/SettingWindowPosition
Here is an example code that return all four corner positions:
from ctypes import POINTER, WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HWND, RECT
# get our window ID:
hwnd = pygame.display.get_wm_info()["window"]
# Jump through all the ctypes hoops:
prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
paramflags = (1, "hwnd"), (2, "lprect")
GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
# finally get our data!
rect = GetWindowRect(hwnd)
print "top, left, bottom, right: ", rect.top, rect.left, rect.bottom, rect.right
# bottom, top, left, right: 644 98 124 644
There is a pygame.display.get_wm_info() call that gets you the Window handler -- from then on, it is using either X11 or Windows API32 to get information from the window through this handler. I didn't find any readily available information on how to do that.
So, just to be clear: there is no ordinary way to do that from within pygame. You have to proceed with another library, possibly using ctypes, after you get the window handler.
On the other hand, if you have to manipulate the window itself, maybe pygame is not the most suitable library for you to use -- you could try PyQt or even GTK+ - they also provide multmedia facilites while being more proper to operate on the level of GUI Windows and other controls
update There are ways to setup an OpenGL backend for pygame graphics, that will allow complete control of the display - including embedding it in another window, as part of a tkinter or Qt application. People that are interested can search a little deeper along those lines.
In Pygame 2, you can alternatively import the _sdl2.video to set the window position. Note that this module is experimental and could be changed in future versions.
import pygame
from pygame._sdl2.video import Window
pygame.init()
window = Window.from_display_module()
window.position = your_position_tuple
Using environment variables as mentioned in other answers is sufficient for most cases, but the downside is that once you have change the window position it will not work a second time (at least in Pygame 2).
Pygame is based on Simple DirectMedia Layer (SDL). Hence you can set SDL environment variables.
See pygame wiki - SettingWindowPosition:
You can set the position of the window by using SDL environment variables before you initialise pygame. Environment variables can be set with the os.environ dict in python.
x = 100
y = 0
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
import pygame
pygame.init()
screen = pygame.display.set_mode((100,100))
(0,0) remains the upper left corner whether the window is moved or not. If you're trying to make (0,0) stay physically where it was on the screen when the window initialized, I don't think pygame can do that. Try to make your question clearer if you want clearer answers.
To accomplish this where you don't know the monitor size of the user, use screeninfo in addition to the pygame and os packages. Screeninfo is OS-agnostic, meaning you can get the resolution of all monitors regardless of a users operating system.
import pygame
from screeninfo import get_monitors
import os
# Set the size of the pygame window
window_width = 512
window_height = 288
window_size = (window_width, window_height)
# Get the bounds of the users monitors, and select the first one
monitors = get_monitors() # Get the resolution of all of the users monitors
screen_width = monitors[0].width # Get width of first monitor found
screen_height = monitors[0].height # Get height of first monitor found
# Set the x and y coordinates of the pygame window in relation to the monitor's resolution
# (I wanted my pygame window to be located in the bottom-right of the monitor)
pos_x = screen_width - window_width # Calculate the x-location
pos_y = screen_height - window_height # Calculate the y-location
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y) # Set pygame window location
pygame.init() # Initialize the pygame window
self.screen = pygame.display.set_mode(size) # Set the location of the pygame window
I wrote a Python 3.7 program with Turtle Graphics. It is a simple program and works fine, but I want it to run full-screen when I initiate the program. How can I do this? There is no full-screen option in the Turtle documentation.
import turtle
from turtle import *
a = turtle.Turtle()
a.speed(10)
a.color('red', 'blue')
# a.begin_fill()
for i in range(90):
a.fd(200)
a.lt(169)
# a.end_fill()
turtle.done()
The width and height arguments to the setup() method take integer (pixel) and floating point (percentage of screen). By supplying 1.0 you'll get the largest window that turtle can make:
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width=1.0, height=1.0)
a = Turtle()
a.speed('fastest')
a.color('red', 'blue')
# a.begin_fill()
for _ in range(36):
a.forward(200)
a.left(170)
# a.end_fill()
screen.mainloop()
But this isn't necessarily the operating systems sense of Full Screen where the window overlays everything. It's just the largest window turtle can create given available screen real estate.
I tried to program the tic tac toe game with PySFML but when I click window by the mouse after some time (10 seconds) application crashes (freezing). Simple code:
from sfml import sf
w = sf.RenderWindow(sf.VideoMode(600,400),"pySFML Window")
WIDTH = 600
HEIGHT = 400
w.size = (WIDTH, HEIGHT)
w.clear(sf.Color.GREEN)
w.title = "Window"
while(True):
if(sf.Keyboard.is_key_pressed(sf.Keyboard.ESCAPE)):
w.close()
w.display()
Is it a bug in pySFML? I don't have this problem in C++ and SFML library.
I use Python3.5 and newest version of PySFML.
The problem you're encountering is inherent to the behavior of SFML, not these bindings. You must have, somewhere, an event loop (which is for event in windows.events: pass) and your code will work.