首页 文章

关于Tkinter的几个问题 - 主循环,更新方法,有效性等

提问于
浏览
0

背景:我正在尝试为在Tkinter之上构建的python编写图形库 . 因此,我想从用户那里抽象出Tkinter的所有功能,并进行方法调用,以类似处理的方式顺序修改根窗口 . 例如我的库(让我们称之为mylib)将使您能够编写如下代码:

from mylib import * #this would be my library
window(400, 400) #open a new window to add objects to
color('red') #set the color of all subsequent items to red
circle(radius=5, centerx = 0, centery=0) #make a red circle
line(10,10, 20, 20) #red line going from (10, 10) to (20, 20)
color('blue')
line(50, 50, 100, 100) #blue line

我想过像这样实现它:

try:
    from tkinter import *
except:
    from Tkinter import *

_root = Tk()


class MyCanvas(Canvas):
    def __init__(self, width=400, height=400):
        master = Toplevel(_root)
        Canvas.__init__(self, master, width=width, height=height)
        self.pack()
        self.items = []
        self.width = width
        self.height = height
        _root.mainloop()


global _c
_c = None

def window():
    _c = MyCanvas()
    _c.pack()

def line(a,b,c,d):
    #config code goes here
    _c.create_line(a,b,c,d)

#test
window()
line(10, 10, 50, 50)

这不起作用,因为Python不会离开mainloop()所以我尝试了这个:尝试:从tkinter import *除了:来自Tkinter import *

_root = Tk()


class MyCanvas(Canvas):
    def __init__(self, width=400, height=400):
        master = Toplevel(_root)
        Canvas.__init__(self, master, width=width, height=height)
        self.pack()
        self.items = []
        self.width = width
        self.height = height



global _c
_c = None

def window():
    _c = MyCanvas()
    _c.pack()

def line(a,b,c,d):
    #config code goes here
    _c.create_line(a,b,c,d)
    _root.update_idletasks()

#test
window()
line(10, 10, 50, 50)

但这也行不通 - 它只是冻结了 . 我尝试用update替换update_idletasks . 窗户又冻结了 . 如何正确使用更新?

有没有办法使用mainloop()完成此操作而无需用户明确调用它?

或者有没有办法在mainloop中编辑小部件?我考虑过使用后,但我没有看到这将如何解决问题 .

如果没有给出答案,这些约束会在PyOpenGL中编写包有用还是可移植?我应该从头开始使用C编写模块吗?还有其他什么吗?帮我!!!

很抱歉这个问题很长 . 我已经在这几个小时了,现在无济于事 .

1 回答

  • 0

    在我看来,你可能最好把它写成一个tcl实现并使用wish作为可执行文件 . 您似乎正在做的是定义特定于域的语言(DSL),您将其解释为驱动Tk的命令 . 似乎没有任何特别需要python的东西 .

    你需要一个主循环 . 任何窗口应用程序都必须有一个事件泵,它从系统获取消息并根据需要将它们分派到您的窗口 . 所有这些应用程序必须最终在主UI线程刚刚泵送此消息队列的位置 . 在Tk wish可执行文件的情况下,它被内置到解释器中 . 希望您的脚本然后运行事件循环 . 您可以通过加载客户端代码并将应用程序主函数作为事件后调用来在python库中模拟它 . 您可能必须确保客户端代码不会调用mainloop以避免冲突 .

    如果你以前从未看过Tcl / Tk - 你可能想要 . 您定义的内容看起来与Tcl / Tk应用程序的距离不是很远 .

相关问题