Time to talk about horizontal menubar. We will have options to ping Google and Yahoo, using os module.
Simple functions that will do pinging:
def pg():
os.system("ping google.com")
def py():
os.system("ping yahoo.com")
Menu will be created in top_win:
bar = Menu(top_win)
Time to add buttons that will be connected to corresponding functions:
bar.add_command(label = "Ping Google", command = pg)
bar.add_command(label = "Ping Yahoo", command = py)
But also we need to activate menu in top_win, before mainloop:
top_win.config(menu = bar)
This is full working source:
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("800x800")
def pg():
os.system("ping google.com")
def py():
os.system("ping yahoo.com")
bar = Menu(top_win)
bar.add_command(label = "Ping Google", command = pg)
bar.add_command(label = "Ping Yahoo", command = py)
top_win.config(menu = bar)
top_win.mainloop()
We can also have menu which is found in most of the editors. Make sure that this source is working on your machine.
Once you run it, what is clicked will be printed in Python Shell. This is just a simple presentation how to connect buttons to vertical menus. In real life scenario our functions will be probably more advanced than printing stuff on screen.
from tkinter import *
import tkinter.messagebox as mb
import os
top_win = Tk()
top_win.geometry("800x800")
bar = Menu(top_win)
def new():
print("New Clicked")
def open_file():
print("Open File Clicked")
file = Menu(bar)
file.add_command(label = "New", command = new)
file.add_command(label = "Open", command = open_file)
file.add_command(label = "Save")
file.add_command(label = "Save As")
file.add_command(label = "Close")
file.add_command(label = "Exit")
bar.add_cascade(label = "File", menu = file)
top_win.config(menu = bar)
top_win.mainloop()
There is also YouTube tutorial on how to create Menubar and Menus with Tkinter.
No comments:
Post a Comment