背景:我正在嘗試爲構建在Tkinter之上的python編寫一個圖形庫。因此,我想從用戶那裏抽取所有Tkinter的功能,並以類似處理的方式依次修改根窗口的方法調用。例如,我的圖書館(我們稱之爲MYLIB)將使你寫這樣的代碼:關於Tkinter的幾個問題 - 主循環,更新方法,效果等
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不會走出主循環的(),所以我嘗試這樣做,而不是: 嘗試: 從Tkinter的進口* 除外: 從Tkinter的進口*
_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()而不需要用戶明確地調用它?
或者有沒有辦法在主循環中編輯小部件?我想過使用後,但我沒看到這將如何解決問題。
如果沒有答案退出給出這些約束會寫在PyOpenGL的包是有用的或便攜式?我應該從頭開始用C編寫模塊嗎?還有其他的東西嗎?幫我!!!
對不起,長期以來的問題。我已經在這幾個小時了,但無濟於事。
簡短的回答:你需要主循環。 –
如何?更新工作,但只是停止響應。沒有線程和處理callbakcs的方法嗎? –
使用_root.mainloop()作爲腳本的最後一行... –