Thursday, June 16, 2016

Python sample program tutorial

Here is a beginner learning / basic Python program to create a small desktop app / widget for fun:

#Name Picker
#from usingpython.com

#import the modules we need, for creating a GUI...
import tkinter
#...and for picking random names.
import random

#the list of possible names.
names = ['name1','name2','name3','name4','name5','name6','name7','name8','name9','name10']

#a function that will pick (and display) a name.
def pickName():
    nameLabel.configure(text=random.choice(names))

#create a GUI window.
root = tkinter.Tk()
#set the title.
root.title("Name Picker")
#set the size.
root.geometry("200x100")

#add a label for displaying the name.
nameLabel = tkinter.Label(root, text="", font=('Helvetica', 32))
nameLabel.pack()

#add a 'pick name' button
pickButton = tkinter.Button(text="Pick!", command=pickName)
pickButton.pack()

#start the GUI 
root.mainloop()

This was my first desktop applictaion built in Python. Took less than 5 minutes.
source : http://usingpython.com/

This is another test program using tkinter package:

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()

source: http://www.python-course.eu/

No comments:

Post a Comment