2013-06-14 2 views
0

Я начинаю программировать на python &. Я пытаюсь создать пустой шаблон, похожий на вид (вроде!) Для моей программы tkinter.Свойства объекта доступа Python tkinter

У меня есть 2 скрипта. один для основной программы, а другой для всех функций. Моя идея - импортировать скрипт с функциями в основной скрипт и использовать шаблон.

мой основной сценарий здесь (main.py):

import module1 as md1 
import Tkinter as tk 

main_sizex=1280 
main_sizey=750 
main_posx=1 
main_posy=1 
main_title="Hello! This is a test" 
main_titlesize=22 
root=tk.Tk() 
md1.Drag_Window(root, main_sizex, main_sizey, main_posx, main_posy, main_title, main_titlesize) 
root.mainloop() 

мой другой скрипт с функциями (module1.py):

import Tkinter as tk 
def Drag_Window(name,sizex,sizey,posx,posy,title,titlesize): 
    def StartMove(event): 
     global x,y 
     x = event.x 
     y = event.y 
    def StopMove(event): 
     x = None 
     y = None 
    def OnMotion(event): 
     x1 = x 
     y1 = y 
     x2 = event.x 
     y2 = event.y 
     deltax = x2-x1 
     deltay = y2-y1 
     a = name.winfo_x() + deltax 
     b = name.winfo_y() + deltay 
     name.geometry("+%s+%s" % (a, b)) 

    name.overrideredirect(True) 
    name.config(relief='solid',bd=1,bg='white') 
    name.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) 
    frame=tk.Frame(name,width=sizex,height=80,relief='solid',bd=1,bg='black') 
    frame.place(x=0,y=0) 
    frame.bind("<ButtonPress-1>",StartMove) 
    frame.bind("<ButtonRelease-1>",StopMove) 
    frame.bind("<B1-Motion>",OnMotion) 
    label=tk.Label(frame,text=title,font=('calibri',(titlesize)),bg='black',fg='white') 
    label.place(x=10,y=15) 
    button=tk.Button(frame,text='EXIT',font=('calibri',(13)),bg='red',relief='flat',bd=1,width=8,pady=3,command=name.destroy) 
    button.place(x=1170,y=20) 
    frame2=tk.Frame(name,width=sizex,height=20,relief='solid',bd=1,bg='black') 
    frame2.place(x=0,y=sizey-20) 

Моя проблема заключается в том, что мне нужно изменить некоторые из свойства, такие как bgcolor и text для некоторых виджетов ярлыков и виджетов кнопок в моем шаблоне. Я знаю, что я могу добавить в дополнительных свойствах я хочу к моей функции как этого

def Drag_Window(name,sizex,sizey,posx,posy,title,titlesize,propertyA,propertyB,...etc): 
........ 
........ 

Но мне интересно, если я могу получить доступ к свойствам виджетов непосредственно из моего основного сценария? В любом случае я могу это сделать?

Что-то вроде этого:

import module1 as md1 
import Tkinter as tk 

main_sizex=1280 
main_sizey=750 
main_posx=1 
main_posy=1 
main_title="Hello! This is a test" 
main_titlesize=22 
root=tk.Tk() 
md1.Drag_Window(root, main_sizex, main_sizey, main_posx, main_posy, main_title, main_titlesize) 
md1.button.config(bg='green') # <= 
root.mainloop() 

ответ

1

Использование class.

main.py

import Tkinter as tk 

import module1 as md1 


main_sizex = 1280 
main_sizey = 750 
main_posx = 1 
main_posy = 1 
main_title = "Hello! This is a test" 
main_titlesize = 22 
root = tk.Tk() 
window = md1.Drag_Window(root, main_sizex, main_sizey, main_posx, main_posy, main_title, main_titlesize) 
window.button.config(bg='green') 
root.mainloop() 

module1.py

import Tkinter as tk 

class Drag_Window: 
    def __init__(self, name, sizex, sizey, posx, posy, title, titlesize): 
     self.name = name 
     name.overrideredirect(True) 
     name.config(relief='solid', bd=1, bg='white') 
     name.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) 
     frame = tk.Frame(name, width=sizex, height=80, relief='solid', bd=1, bg='black') 
     frame.place(x=0, y=0) 
     frame.bind("<ButtonPress-1>", self.StartMove) 
     frame.bind("<ButtonRelease-1>", self.StopMove) 
     frame.bind("<B1-Motion>", self.OnMotion) 
     label = tk.Label(frame, text=title, font=('calibri', titlesize), bg='black', fg='white') 
     label.place(x=10, y=15) 
     self.button = tk.Button(frame, text='EXIT', font=('calibri', 13), bg='red', relief='flat', bd=1, width=8, pady=3, command=name.destroy) 
     self.button.place(x=1170, y=20) 
     frame2 = tk.Frame(name, width=sizex, height=20, relief='solid', bd=1, bg='black') 
     frame2.place(x=0, y=sizey-20) 

    def StartMove(self, event): 
     self.x = event.x 
     self.y = event.y 

    def StopMove(self, event): 
     self.x = None 
     self.y = None 

    def OnMotion(self, event): 
     x1 = self.x 
     y1 = self.y 
     x2 = event.x 
     y2 = event.y 
     deltax = x2 - x1 
     deltay = y2 - y1 
     a = self.name.winfo_x() + deltax 
     b = self.name.winfo_y() + deltay 
     self.name.geometry("+%s+%s" % (a, b)) 

Другой способ (не рекомендуется) - выставить виджеты как глобальную переменную в Drag_Window (функции).

def Drag_Window(root, ....): 
    global button 
    .... 
    button = Button(....) 
+0

BTW, 'name' не является хорошим именем. Вместо этого используйте 'parent' или' master'. – falsetru

+0

WOW! Большое спасибо . я не ожидал, что вы напишете весь ответ ... изначально я был отброшен концепцией класса, но, прочитав ваш пример, он делает некоторые из моих сомнений ясными. еще раз .. спасибо: D –

Смежные вопросы