如何在Python(Tkinter)中获取Windows屏幕尺寸
获取Windows屏幕尺寸的Python解决方案(基于tkinter)
问题背景
我在Windows系统上做一个Python项目(用tkinter开发),需要获取屏幕尺寸来替代固定的900x500窗口大小。我是Python业余爱好者,主要用Python做兴趣项目和大学作业。
最初的固定尺寸代码:
from tkinter import * import random as rd import numpy as np import time class game : def __init__(self): self.screen = Tk() #screen size self.screen.geometry("900x500") #the rest is not essential to understand my problem self.screen.mainloop() game()
我试过YouTube上的方法,但缺少对应模块;之后参考代码用了Gtk,但不知道Gtk是什么,搜出来都是C语言相关内容,找不到对应的Python模块,希望得到帮助。
解决方案:用tkinter自带方法获取屏幕尺寸
既然你已经在使用tkinter,完全不需要额外安装任何模块,直接用tkinter内置的方法就能拿到屏幕尺寸,修改后的代码如下:
from tkinter import * import random as rd import numpy as np import time class game : def __init__(self): self.screen = Tk() # 获取屏幕宽高 screen_width = self.screen.winfo_screenwidth() screen_height = self.screen.winfo_screenheight() # 设置窗口为屏幕尺寸(也可以按比例调整,比如`f"{int(screen_width*0.8)}x{int(screen_height*0.8)}"`) self.screen.geometry(f"{screen_width}x{screen_height}") # 其他代码 self.screen.mainloop() game()
关于Gtk的说明
Gtk是一套跨平台GUI工具包,主要用于Linux桌面程序开发,它的Python绑定(pygobject)在Windows上安装配置繁琐,对你的tkinter项目来说完全没必要,用tkinter自带方法更简单直接。
内容的提问来源于stack exchange,提问作者Moh
相关产品推荐
相关产品推荐

