问题描述
我有一个通过graphics.py
部署Windows的python程序。由GraphWin
类打开的初始窗口在屏幕的左上角打开。随后对GraphWin
的调用从左上角到右下角。
我想控制每个窗口的位置。 (示例:在网格布局中打开所有窗口,以便创建仪表板。)
解决方法
我认为graphics.py中目前没有这种方法。
如果您要坚持使用graphics.py,我建议通过将单个窗口划分为不同的插槽来创建仪表板。
该选项在Tkinter库中确实存在。有关更多信息,请参考this答案。
, graphics.py
无法为您提供控制其GraphWin
类实例的位置的方法。但是,它基于Python的tkinter
的Tk GUI工具包模块而建立的事实意味着,有时您可以通过查看其源代码以了解事物在内部的运行方式来解决其局限性。
例如,这是模块(版本5.0)中的代码片段,显示了GraphWin
文件中graphics.py
类的定义的开始:
class GraphWin(tk.Canvas):
"""A GraphWin is a toplevel window for displaying graphics."""
def __init__(self,title="Graphics Window",width=200,height=200,autoflush=True):
assert type(title) == type(""),"Title must be a string"
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW",self.close)
tk.Canvas.__init__(self,master,width=width,height=height,highlightthickness=0,bd=0)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>",self._onClick)
self.bind_all("<Key>",self._onKey)
self.height = int(height)
self.width = int(width)
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
self.lastKey = ""
if autoflush: _root.update()
如您所见,它源自tkinter.Canvas
小部件,该小部件具有名为master
的属性,该属性是tkinter.Toplevel
小部件。然后,它将初始化Canvas
基类,并将新创建的Toplevel
窗口指定为其父窗口。
如链接文档中所述,可以通过调用Toplevel
方法来控制geometry()
窗口的大小和位置。该方法期望在certain format('wxh±x±y'
)中传递“几何字符串”参数。
这意味着您可以利用此实现方式的细节,以便将其放置在所需的任何位置,并根据需要调整大小。
这是这样做的一个例子:
from graphics import *
def main():
win = GraphWin("My Circle",100,100)
# Override size and position of the GraphWin.
w,h = 300,300 # Width and height.
x,y = 500,500 # Screen position.
win.master.geometry('%dx%d+%d+%d' % (w,h,x,y))
c = Circle(Point(50,50),10)
c.draw(win)
win.getMouse() # pause for click in window
win.close()
if __name__ == '__main__':
main()
脚本运行时我的桌面: