Python Tkinter如何调整x,y默认0,0坐标

内霍

我一直在学习一些基本的tkinter,并且遇到了一些简单的代码来将窗口居中放置在监视器的中间,除了运行时它是水平关闭的。这很花哨,但让我很困扰。我使用的代码

# Imports
from tkinter import *

# tkinter Application
root = Tk()

#Root Geometry
root_Width = 600
root_Length = 600

# Coordinates of top left pixel of application for centred
x_left = int(root.winfo_screenwidth()/2-root_Width/2)
y_top = int(root.winfo_screenheight()/2-root_Length/2)
root_Pos = "+" + str(x_left) + "+" + str(y_top)

# Window size and position
root.geometry(str(root_Width) + "x" + str(root_Length) + root_Pos)

root.mainloop()

即使我基本操作,只是尝试打开显示器大小(1920x1080)为0,0的窗口,它也会在水平方向上错位8px。

from tkinter import *

root = Tk()
root.geometry("1920x1080+0+0")
root.mainloop()

我截取了以下结果的屏幕截图:
屏幕截图
我设置了双监视器,因此我在正确的监视器开始处添加了一条红线。我不知道问题是什么或如何解决。如果我改成

root.geometry("1920x1080+-8+0")

It opens where it should, but I want to fix this in general preferably. I want 0,0 to be the top left pixel of the monitor. I acknowledge the issue may not be with python, but any advice would be helpful.

Flavio Moraes

Ok, there are two thing that you are missing. The first, in your first example, is that you need to assure tkinter is getting the right values, and to do this you have to use update_idletasks() method before any winfo.

第二件事解释了为什么您必须使用-8全屏窗口居中,这是tkinter寡妇具有外部框架。您可以通过检查窗口(winfo_rootx())和外部框架(winfo_x())的左上角坐标来确定该框架的大小现在,框架宽度是两者之间的差异:frame_width = root.winfo_rootx() - root.winfo_x()而实际窗口宽度是real_width = root.winfo_width() + (2*frame_width),因为您必须考虑两侧的框架。

总之,要使窗口水平居中,请执行以下操作:

width = root.winfo_width()
frame_width = root.winfo_rootx() - root.winfo_x()
real_width = root.winfo_width() + (2*frame_width)
x = root.winfo_screenwidth() // 2 - real_width // 2

(在这里您可以打印框架宽度,您将看到它是8

然后使用geometry方法将窗口放置在位置x

当然,您可以对垂直对齐进行相同的操作

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Python中使用matplotlib使x轴穿过(0,0)?

如何使用opencv将两个鼠标坐标[[x0,y0),(x1,y1)]导出到python中的txt文件中

Python:使用到点A的距离(x0,y0)和角度找到给定点B的x,y坐标

如何通过触摸获取imageview的中心坐标(x,y)(0,0)

如何从(0,0)坐标移动面板

为什么在Python中“ 0,0 ==(0,0)”等于“(0,False)”?

通过将Imageview的左上角视为(0,0)获得Imageview的X,Y坐标

Python排序问题x [y [:,0]> 50]

如何在python中计算x,y坐标的质心

Python图形库:如何设置窗口的x和y坐标?

这种python索引如何工作:'print(X_train [y_train == 0] [0])'在python中工作?

如何使用python生成均匀分布在以(0,0)为中心的40 * 40矩形区域上的随机点?

如何使用Python Altair将x轴和y轴的交点从0移位到1?

Jcanvas坐标不是从(0,0)开始

识别python x,y数组中的x,y坐标对

如何使用Python提取点的x坐标

如何在PIL python中获得已旋转角度的文本的x,y坐标?

如何在python中为(x,y)坐标点着色

如何从python中的mathplot中识别某个y值的所有x坐标值

如何在python中使用x和y坐标验证ES384 JWT签名

如何获取在OpenCV,Python中使用遮罩找到的形状的(x,y)坐标?

如何将乌龟的y坐标提取为浮点数-Python 3.x

如何从python中的2D列表中获取最大x和最小y坐标?

使用d3.js将x轴移动到图表上的坐标(0,0)

EXEC:EXEC(0,0):错误:找不到:python2

python 海龟在使用 tracer(0,0) 时创建闪烁的图像

Python图形x轴反转,如何显示0到n?

Python Tkinter Checkbutton值始终等于0

如何使用 For 循环生成从 0,0 到 5,5 的坐标?