2017年8月28日 星期一

Tkinter Button 範例





from tkinter import Tk, Button

def goodbye_world():
    print ("Goodbye World!\nWait, I changed my mind!")
    button.configure(text = "Hello World!", command=hello_world)

def hello_world():
    print ("Hello World!\nWait, I changed my mind!")
    button.configure(text = "Goodbye World!", command=goodbye_world)

root = Tk()
button = Button(root, text="Hello World!", command=hello_world)
button.pack()

root.mainloop()

Tkinter intro


Tkinter intro




In this video, we begin discussion of the tkinter module. The tkinter module is a wrapper around tk, which is a wrapper around tcl, which is what is used to create windows and graphical user interfaces. Here, we show how simple it is to create a very basic window in just 8 lines. We get a window that we can resize, minimize, maximize, and close! The tkinter module's purpose is to generate GUIs. Python is not very popularly used for this purpose, but it is more than capable of doing it.
Let's walk through each step to making a tkinter window:
Simple enough, just import everything from tkinter.
from tkinter import *
Here, we are creating our class, Window, and inheriting from the Frame class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
Then we define the settings upon initialization. This is the master widget.
class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)               
        self.master = master
The above is really all we need to do to get a window instance started.
Root window created. Here, that would be the only window, but you can later have windows within windows.
root = Tk()
Then we actually create the instance.
app = Window(root)
Finally, show it and begin the mainloop.
root.mainloop()
The above code put together should spawn you a window that looks like:
tkinter python 3 tutorial
Pretty neat, huh? Obviously there is much more to cover.
The next tutorial: 



Tkinter 攝氏溫度轉華視溫度



# -*- coding: UTF-8 -*-
from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        value = float(Cels.get())
        Fahr.set( value * (9/5) +32)
    except ValueError:
        pass
    
root = Tk()
root.title("******   攝氏溫度 轉 華式溫度   *******")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

Cels = StringVar()
Fahr = StringVar()

feet_entry = ttk.Entry(mainframe, width=7, textvariable=Cels)
feet_entry.grid(column=2, row=1, sticky=(W, E))

ttk.Label(mainframe, textvariable=Fahr).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=1, row=3, sticky=E)
ttk.Button(mainframe, text="Quit", command= quit).grid(column=2, row=3, sticky=E)


ttk.Label(mainframe, text="請輸入 攝氏溫度 == ").grid(column=1, row=1, sticky=E)
ttk.Label(mainframe, text="     相當於    ").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="華式溫度").grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind('<Return>', calculate)

root.mainloop()

2017年8月27日 星期日

Message Widget

The syntax of a message widget: 

w = Message ( master, option, ... ) 


The Options in Detail

OptionMeaning
anchorThe position, where the text should be placed in the message widget: N, NE, E, SE, S, SW, W, NW, or CENTER. The Default is CENTER.
aspectAspect ratio, given as the width/height relation in percent. The default is 150, which means that the message will be 50% wider than it is high. Note that if the width is explicitly set, this option is ignored.
backgroundThe background color of the message widget. The default value is system specific.
bgShort for background.
borderwidthBorder width. Default value is 2.
bdShort for borderwidth.
cursorDefines the kind of cursor to show when the mouse is moved over the message widget. By default the standard cursor is used.
fontMessage font. The default value is system specific.
foregroundText color. The default value is system specific.
fgSame as foreground.
highlightbackgroundTogether with highlightcolor and highlightthickness, this option controls how to draw the highlight region.
highlightcolorSee highlightbackground.
highlightthicknessSee highlightbackground.
justifyDefines how to align multiple lines of text. Use LEFT, RIGHT, or CENTER. Note that to position the text inside the widget, use the anchor option. Default is LEFT.
padxHorizontal padding. Default is -1 (no padding).
padyVertical padding. Default is -1 (no padding).
reliefBorder decoration. The default is FLAT. Other possible values are SUNKEN, RAISED, GROOVE, and RIDGE.
takefocusIf true, the widget accepts input focus. The default is false.
textMessage text. The widget inserts line breaks if necessary to get the requested aspect ratio. (text/Text)
textvariableAssociates a Tkinter variable with the message, which is usually a StringVar. If the variable is changed, the message text is updated.
widthWidget width given in character units. A suitable width based on the aspect setting is automatically chosen, if this option is not given.

Python 的內建 GUI 模組 Tkinter 建立視窗 -----Message Widget



from tkinter import *
master = Tk()
whatever_you_do = "Whatever you do will be insignificant, but it is very important that you do it.\n(Mahatma Gandhi)"
msg = Message(master, text = whatever_you_do)
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.pack( )
mainloop( )

Python 的內建 GUI 模組 Tkinter 建立視窗 ----Dynamical Content in a Label



import tkinter as tk

counter = 0 
def counter_label(label):
  def count():
    global counter
    counter += 1
    label.config(text=str(counter))
    label.after(1000, count)
  count()


root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()

Python 的內建 GUI 模組 Tkinter 建立視窗----Colorized Labels in various fonts







from tkinter import *

root = Tk()

Label(root, 
text="Red Text in Times Font",
fg = "red",
font = "Times").pack()
Label(root, 
text="Green Text in Helvetica Font",
fg = "light green",
bg = "dark green",
font = "Helvetica 16 bold italic").pack()
Label(root, 
text="Blue Text in Verdana bold",
fg = "blue",
bg = "yellow",
font = "Verdana 10 bold").pack()

root.mainloop()