python-snippet/gui/gui_example_tk.py

68 lines
2.2 KiB
Python
Raw Permalink Normal View History

"""From http://sebsauvage.net/python/gui/"""
import tkinter as tk
class my_tk_app(tk.Tk):
"""This class holds the main window"""
def __init__(self, parent):
"""We use the parent constructor and keep track of our parent"""
tk.Tk.__init__(self, parent)
self.parent = parent
self.initialise()
def initialise(self):
"""To separate GUI from logic, we create widgets here"""
# Create the layout manager
self.grid()
# Create and keep a reference to a text entry
self.entryVariable = tk.StringVar()
self.entry = tk.Entry(self, textvariable=self.entryVariable)
self.entry.grid(column=0, row=0, sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entryVariable.set(u"Entrez du texte ici.")
# Create a button
button = tk.Button(self, text=u"Cliques moi !",
command=self.OnButtonClick)
button.grid(column=1, row=0)
# Create a label
self.labelVariable = tk.StringVar()
label = tk.Label(self, textvariable=self.labelVariable,
anchor='w', fg='white', bg='blue')
label.grid(column=0, row=1, columnspan=2, sticky='EW')
self.labelVariable.set(u"Salut !")
# Allow content to be resized with window
self.grid_columnconfigure(0, weight=1)
# Enable resizing horizontally, not vertically
self.resizable(True, False)
# tk will change win size according to content
# so we update to compute size, and we fix it
self.update()
self.geometry(self.geometry())
# Default focus to the text entry
self.entry.focus_set()
self.entry.selection_range(0, tk.END)
def OnButtonClick(self):
self.labelVariable.set(self.entryVariable.get() + " (bouton)")
self.entry.focus_set()
self.entry.selection_range(0, tk.END)
def OnPressEnter(self, event):
self.labelVariable.set(self.entryVariable.get() + " (entrée)")
self.entry.focus_set()
self.entry.selection_range(0, tk.END)
if __name__ == "__main__":
app = my_tk_app(None)
app.title("My tkinter application")
app.mainloop()