i know that i can create menu bar with add_cascade
like this code:
from tkinter import *
from tkinter.ttk import *
from time import strftime
# creating tkinter window
root = Tk()
root.title('Menu Demonstration')
# Creating Menubar
menubar = Menu(root)
# Adding File Menu and commands
file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
file.add_separator()
file.add_command(label ='Exit', command = root.destroy)
# Adding Edit Menu and commands
edit = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_command(label ='Select All', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)
# Adding Help Menu
help_ = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Help', menu = help_)
help_.add_command(label ='Tk Help', command = None)
help_.add_command(label ='Demo', command = None)
help_.add_separator()
help_.add_command(label ='About Tk', command = None)
# display Menu
root.config(menu = menubar)
mainloop()
But how can i remove them?
You can use delete to delete a menubar
menubar.delete ( 'name' )
Related
I am trying to make a GUI program using tkinter and python3. When I try to create a submenu for a menu in the menubar, I get a 3D arrow unlike the arrow I usually get in other programs.
from tkinter import *
MainWindow = Tk()
MainWindow.title('MenuBar')
MainWindow.geometry(str(MainWindow.winfo_screenwidth()) + 'x' + str(MainWindow.winfo_screenheight()))
#Menu_Bar object
menubar = Menu(MainWindow, bd=0, activeborderwidth=0)
#File Menu Object
file_menu = Menu(menubar, tearoff = 0, bd=0, activeborderwidth=0)
file_menu.add_command(label =' New', command = None)
file_menu.add_separator()
file_menu.add_command(label =' Open', command = None)
#Create a sub-menu for Open-Recent
Open_Recent = Menu(file_menu, tearoff=0, bd=0,activeborderwidth=0)
Open_Recent.add_command(label = 'file1', command=None)
Open_Recent.add_command(label = 'file2', command=None)
Open_Recent.add_command(label = 'file3', command=None)
file_menu.add_cascade(label =' Open Recent', command = None, menu=Open_Recent)
file_menu.add_separator()
file_menu.add_command(label =' Save', command = None)
file_menu.add_command(label =' Save as', command = None)
file_menu.add_separator()
file_menu.add_command(label =' Import FIle as Module', command = None)
file_menu.add_separator()
file_menu.add_command(label =' Exit', command = MainWindow.destroy)
menubar.add_cascade(label ='Menu', menu = file_menu)
#Edit Menu Object
edit_menu = Menu(menubar, tearoff = 0, bd=0, activeborderwidth=0)
edit_menu.add_command(label =' Undo', command = None)
edit_menu.add_command(label =' Redo', command = None)
edit_menu.add_separator()
edit_menu.add_command(label =' UI', command = None)
edit_menu.add_command(label =' System', command = None)
edit_menu.add_separator()
edit_menu.add_command(label =' Rename', command = None)
edit_menu.add_command(label =' Batch Rename', command = None)
menubar.add_cascade(label ='Edit', menu = edit_menu)
#Assets Menu Object
Asset_menu = Menu(menubar, tearoff = 0, bd=0, activeborderwidth=0)
Asset_menu.add_command(label =' Set Folder', command = None)
Asset_menu.add_command(label =' Export as Asset', command = None)
Asset_menu.add_command(label =' Import Asset', command = None)
Asset_menu.add_command(label =' Browse Assets', command = None)
Asset_menu.add_command(label =' Set Icon', command = None)
Asset_menu.add_command(label =' Remove Icon', command = None)
menubar.add_cascade(label =' Assets', menu = Asset_menu)
#Adding Menubar to the window
MainWindow.config(menu=menubar)
mainloop()
Here is a screenshow from VSCode(the look I am going for)
Image1
And here is what I am getting
Image2
I just added bg = "black", fg = "white",activebackground="white" to each menu. I'm not sure if it's the right answer, but the result looks the exactly like image 1.
EDIT:
full code with the small changes.
from tkinter import *
MainWindow = Tk()
MainWindow.title('MenuBar')
MainWindow.geometry(str(MainWindow.winfo_screenwidth()) + 'x' + str(MainWindow.winfo_screenheight()))
#Menu_Bar object
menubar = Menu(MainWindow, bd=0, activeborderwidth=0, bg = "black", fg = "white",activebackground="white")
#File Menu Object
file_menu = Menu(menubar, tearoff = 0, bd=0, activeborderwidth=0, bg = "black", fg = "white",activebackground="white")
file_menu.add_command(label =' New', command = None)
file_menu.add_separator()
file_menu.add_command(label =' Open', command = None)
#Create a sub-menu for Open-Recent
Open_Recent = Menu(file_menu, tearoff=0, bd=0,activeborderwidth=0, bg = "black", fg = "white",activebackground="white")
Open_Recent.add_command(label = 'file1', command=None)
Open_Recent.add_command(label = 'file2', command=None)
Open_Recent.add_command(label = 'file3', command=None)
file_menu.add_cascade(label =' Open Recent', command = None, menu=Open_Recent)
file_menu.add_separator()
file_menu.add_command(label =' Save', command = None)
file_menu.add_command(label =' Save as', command = None)
file_menu.add_separator()
file_menu.add_command(label =' Import FIle as Module', command = None)
file_menu.add_separator()
file_menu.add_command(label =' Exit', command = MainWindow.destroy)
menubar.add_cascade(label ='Menu', menu = file_menu)
#Edit Menu Object
edit_menu = Menu(menubar, tearoff = 0, bd=0, activeborderwidth=0,bg = "black", fg = "white",activebackground="white")
edit_menu.add_command(label =' Undo', command = None)
edit_menu.add_command(label =' Redo', command = None)
edit_menu.add_separator()
edit_menu.add_command(label =' UI', command = None)
edit_menu.add_command(label =' System', command = None)
edit_menu.add_separator()
edit_menu.add_command(label =' Rename', command = None)
edit_menu.add_command(label =' Batch Rename', command = None)
menubar.add_cascade(label ='Edit', menu = edit_menu)
#Assets Menu Object
Asset_menu = Menu(menubar, tearoff = 0, bd=0, activeborderwidth=0,bg = "black", fg = "white",activebackground="white")
Asset_menu.add_command(label =' Set Folder', command = None)
Asset_menu.add_command(label =' Export as Asset', command = None)
Asset_menu.add_command(label =' Import Asset', command = None)
Asset_menu.add_command(label =' Browse Assets', command = None)
Asset_menu.add_command(label =' Set Icon', command = None)
Asset_menu.add_command(label =' Remove Icon', command = None)
menubar.add_cascade(label =' Assets', menu = Asset_menu)
#Adding Menubar to the window
MainWindow.config(menu=menubar)
mainloop()
I have two excel files to import; file1.xls and file2.xls. I have define two separate function to import and third function to merge these files. However, merge is not happening. The error is showing
NameError: Name 'File1' is not defined.
I am using below code. Please help.
from tkinter import messagebox, filedialog, Frame, Button, Tk, Menu
import pandas as pd
def importivl():
global File1
LI_Filepath = filedialog.askopenfilename()
File1 = pd.read_excel(LI_Filepath)
messagebox.showinfo("File1", "File Imported Successfully")
def importcatfile():
global File2
Cat_Filepath = filedialog.askopenfilename()
File2 = pd.read_excel(Cat_Filepath)
messagebox.showinfo("File2", "File Imported Successfully")
def mergeivlcat():
File1 = pd.merge(File1, File2, on = "ID", how = "left")
def phase_one():
frame = Frame(root)
frame.pack()
import_LI_File = Button(root, text = "Import File1", command = importivl).pack()
import_Category_File = Button(root, text = "Import File2", command = importcatfile).pack()
mergeivlcat()
root = Tk()
root.geometry("600x400")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Phase One", command = phase_one)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command = root.destroy)
menubar.add_cascade(label = "File", menu = filemenu)
root.config(menu = menubar)
root.mainloop()
I am new to this tkinter menu. I am trying to upload and display an excel file by using the 'filemenu' in the menubar and 'btnNew' in the toolbar menu.
The application did run but it does not display my excel file after I browse the file. The application only display the datatypes of each variable in the excel file.
import pandas as pd
import xlrd
import tkinter as tk
from tkinter import Frame, Menu, Button, Label, Canvas
from tkinter import LEFT, RIGHT, TOP, BOTTOM, X, FLAT, RAISED
from tkinter import filedialog
from tkinter import ttk
root = tk.Tk() #main method 1 - create main window (parent window)
root.title("Data Visualisation")
width = 1000
height = 500
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))
root.resizable(1,1)
def browseFile():
global workbook, copyWorkbook, excel_file, sheetName, worksheet
fileName = filedialog.askopenfilename(initialdir = '/', title = 'New File', filetypes = (('excel file', '.xlsx'), ('excel file', '.xls'), ('all files', '*.*')))
excel_file = pd.ExcelFile(fileName)
workbook = xlrd.open_workbook(fileName)
sheetCount = workbook.nsheets
#Create tabs
sheetName = []
tab = []
for x in range(workbook.nsheets):
tab.append(ttk.Frame(tabControl))
sheetName = workbook.sheet_names()
tabControl.add(tab[x], text = sheetName[x])
df_table = excel_file.parse(sheetName[x])
print(df_table.dtypes)
lblTable = Label(tab[x], text = df_table.to_string(index = False)).grid()
btnGraph = Button(tab[x], text = "Graph").grid(sticky = 'w', column = 1, row = 5)
##MENU BAR
menubar = Menu(root)
root.config(menu = menubar)
#FILE MENU
filemenu = Menu(menubar, bg = '#BFBFBF', tearoff = 0)
menubar.add_cascade(label = 'File', menu = filemenu)
filemenu.add_command(label = 'New', compound = LEFT, command = browseFile)
filemenu.add_command(label = 'Open...', compound = LEFT)
filemenu.add_separator()
filemenu.add_command(label = 'Quit', compound = LEFT, command = root.quit)
#SEARCH MENU
searchmenu = Menu(menubar, bg = '#BFBFBF')
menubar.add_cascade(label = 'Search', menu = searchmenu)
searchmenu.add_command(label = 'Find...', compound = LEFT)
searchmenu.add_command(label = 'Replace...', compound = LEFT)
#HELP MENU
helpmenu = Menu(menubar, bg = '#BFBFBF')
menubar.add_cascade(label = 'Help', menu = helpmenu)
helpmenu.add_command(label = 'About', compound = LEFT)
##TOOLBAR MENU
toolbar = Frame(root, bd = 1, relief = RAISED)
#To browse excel file
btnNew = Button(toolbar, text = 'New', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 20, pady = 2, command = browseFile).pack(side = LEFT)
btnOpen = Button(toolbar, text = 'Open', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2).pack(side = LEFT)
btnFind = Button(toolbar, text = 'Find', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2).pack(side = LEFT)
btnReplace = Button(toolbar, text = 'Replace', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2).pack(side = LEFT)
btnQuit = Button(toolbar, text = 'Quit', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2, command = root.quit).pack(side = RIGHT)
toolbar.pack(side = TOP, fill = X)
###Tab Widget
tabControl = ttk.Notebook(menubar)
tabHome = ttk.Frame(tabControl)
tabControl.add(tabHome, text = "Home")
#All the automation Tab is pack here
tabControl.pack(expand = 1, fill = 'both', side = LEFT)
root.mainloop() #main method 2 - run the application
The application should display tabs and in each tab, it should contain each sheet from the excel file. All the tabs must be display after the toolbar menu.
I'm not sure what is the problem as is does not specify if there is any error in my code.
All feedback is welcomed as I am trying to learn how to make a better interface using python. Thank you for your help :D
You set the wrong parent to the frame tabControl.
Change:
tabControl = ttk.Notebook(menubar)
to:
tabControl = ttk.Notebook(root)
I am trying to build a xml parser in python, i start to build gui framework, and here i need to create some forms to save some settings values. I manage to make it work and save some values to txt files for startup. But what ever i tried i can't manage to close the settings form when i click button. i need to close it with the x on the window. i can't find the root of the issue.
what i am trying to do is, when i click Cancel, form will be closed. if i click Save, form will first save data then close.
thanks a lot for your supports.
my code is as follows:
try:
# for Python2
print ("Importing for py2");
from Tkinter import * ## notice capitalized T in Tkinter
import tkFileDialog
except ImportError:
# for Python3
print ("Importing for py2 Failed !!!!");
print ("Importing for py3");
from tkinter import *
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import messagebox
mainform = Tk()
mainform.minsize(300,100)
mainform.geometry('{}x{}'.format(800, 600))
mainform.title("OVF Template Parser - By Gurhan Cagin (R) 2018")
textPad = ScrolledText(mainform, width=100, height=80)
textPad.pack()
## functions and procdures
def donothing():
x = 0
def quit():
if messagebox.askokcancel("Quit", "Do you really want to quit?"):
exit()
def about_command():
label = messagebox.showinfo("About", "Nokia OVF Template Parser \nCopyright 2018 \nNo rights left to reserve")
def open_command():
file = filedialog.askopenfile(parent=mainform, mode='rb', title='Select a file')
if file != None:
contents = file.read()
textPad.insert('1.0',contents)
file.close()
def SettingsFormFxn():
settingsForm = Tk()
settingsForm.minsize(300,100)
settingsForm.geometry('{}x{}'.format(750, 550))
settingsForm.title("Settings for the devault values")
## Frames
top_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
bottom_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
settingsForm.grid_rowconfigure(1, weight=1)
settingsForm.grid_columnconfigure(0, weight=1)
top_frame.grid(row=0, sticky="ew")
bottom_frame.grid(row = 4, sticky = "e")
b1 = Label(top_frame, text = "CPU per Core in Ghz:")
b1.grid(row = 0, column = 0)
entryText = StringVar(settingsForm, "2.1")
e1 = Entry(top_frame, textvariable = entryText, width = 5)
e1.grid(row = 0, column = 2)
def SaveFxn():
with open("settings.txt", "w") as f:
f.write(e1.get() + "\n")
##f.write(ent2.get() + "\n")
def CancelFxn():
settingsForm.destroy
cancel = Button(bottom_frame, text = "Cancel", command = CancelFxn, pady = 10, padx = 10,activebackground='grey',activeforeground='#AB78F1',bg='#e87474',highlightcolor='red')
cancel.grid(row = 0, column = 10)
save = Button(bottom_frame, text = "Save", command = SaveFxn, pady = 10, padx = 10)
save.grid(row = 0, column = 11)
settingsForm.mainloop()
## EOF FXNS
## Menu Definitions
menubar = Menu(mainform)
## File Menu
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Open", command = open_command)
filemenu.add_separator()
filemenu.add_command(label="Exit", command = quit)
menubar.add_cascade(label="File", menu=filemenu)
## Settings Menu
settingsmenu = Menu(menubar, tearoff = 0)
settingsmenu.add_command(label = "Settings", command = SettingsFormFxn)
menubar.add_cascade(label="Settings",menu=settingsmenu)
## About Menu
aboutmenu = Menu(menubar, tearoff = 0)
aboutmenu.add_command(label = "About", command = about_command)
menubar.add_cascade(label="Help", menu=aboutmenu)
mainform.config(menu=menubar)
## EOF Menu Definitions
## Main loop
mainloop()
You forgot your parenthesis when trying to call settingsForm.destroy.
def CancelFxn():
settingsForm.destroy()
I am trying to create a GUI program in python to generate random Lottery numbers. I want to have a menu bar for choosing Powerball or MegaMillion. And after choosing it, there will be buttons to let user select how many tickets to show. But I cannot make the method work. I want to show different lines of number lists when I click the button, but it does show anything. I'm not finished yet since it doesn't work. I am new to Python and programming, please help! Thank you !
from tkinter import *
import random
class lotteryNum:
def __init__(self):
window=Tk()
window.title("Lottery Number Generator")
menubar = Menu(window)
window.config(menu=menubar)
self.pbLst = [x for x in range(1,70)]
self.pbLst2=[x for x in range(1,27)]
self.mmLst = [x for x in range(1,76)]
self.mmLst2=[x for x in range(1,16)]
self.usingLst=["*"]*6
#Type Menu
typeMenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Which Lottery", menu = typeMenu)
typeMenu.add_command(label="Powerball", command= self.powerBall)
typeMenu.add_command(label="Mega Milion", command= self.megaMillion)
#Exit menu
exitmenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Exit", menu = exitmenu)
exitmenu.add_command(label = "Quit", command = window.quit)
#Welcome label
Label(window, text="Welcome to Lottery Generator!").pack()
frame=Frame(window)
frame.pack()
#Text Label
self.showResults = StringVar()
Label(frame, text=self.showResults).pack()
Button(window, text="$2", command=self.runLottery()).pack(side=LEFT)
window.mainloop()
def powerBall(self):
# random.shuffle(self.pbLst)
# random.shuffle(self.pbLst2)
self.usingLst=self.pbLst
self.usingLst2=self.pbLst2
def megaMillion(self):
# random.shuffle(self.mmLst)
# random.shuffle(self.mmLst2)
self.usingLst=self.mmLst
self.usingLst2=self.mmLst2
def runLottery(self):
random.shuffle(self.usingLst)
random.shuffle(self.usingLst2)
self.usingLst[:5].extend(self.usingLst2[0])
self.showResults.set(self.usingLst)
lotteryNum()
I think your code should work if you change this line:
Label(frame, text=self.showResults).pack()
to this:
Label(frame, textvariable=self.showResults).pack()
Finished code just let whoever interested know what I'm try to do here.
from tkinter import *
import random
class lotteryNum:
def __init__(self):
window=Tk()
window.title("Lottery Number Generator")
menubar = Menu(window)
window.config(menu=menubar)
self.pbLst = [x for x in range(1,70)]
self.pbLst2=[x for x in range(1,27)]
self.mmLst = [x for x in range(1,76)]
self.mmLst2=[x for x in range(1,16)]
self.usingLst=[0]*6
self.usingLst2=[0]*6
#Type Menu
typeMenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Which Lottery", menu = typeMenu)
typeMenu.add_command(label="Powerball", command= self.powerBall)
typeMenu.add_command(label="Mega Milion", command= self.megaMillion)
#Exit menu
exitmenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Exit", menu = exitmenu)
exitmenu.add_command(label = "Quit", command = window.quit)
#Welcome label
Label(window, text="Welcome to Lottery Generator!").pack()
frame=Frame(window)
frame.pack()
#Text Label to show numbers
self.showResults = StringVar()
self.showResults5=StringVar()
oneTicket=Label(frame, textvariable=self.showResults).pack()
fiveTicket=Message(frame,textvariable=self.showResults5).pack()
#Buttons to generate tickets
Button(window, text="one ticket", command=self.showTicket).pack(side=LEFT)
Button(window, text="five tickets", command=self.showTicket5).pack(side=LEFT)
#Button to draw the tickets
Button(window, text="Draw tickets", command=self.drawTickets).pack()
#The process to draw each ticket
self.covered=False
window.mainloop()
def powerBall(self):
self.usingLst=self.pbLst
self.usingLst2=self.pbLst2
self.runLottery()
self.winingNumbers = self.showLst
def megaMillion(self):
self.usingLst=self.mmLst
self.usingLst2=self.mmLst2
self.runLottery()
self.winingNumbers = self.showLst
def runLottery(self):
random.shuffle(self.usingLst)
random.shuffle(self.usingLst2)
self.showLst=self.usingLst[:5]
self.showLst.sort()
self.showLst.append(self.usingLst2[0])
def showTicket(self):
self.runLottery()
if (self.showLst==self.winingNumbers):
self.covered = True
self.carry1=""
for i in range(6):
self.carry1+=str(self.showLst[i])+" "
self.showResults.set(self.carry1)
def showTicket5(self):
self.showTicket()
self.carry5=""
for i in range(4):
self.runLottery()
if(self.showLst==self.winingNumbers):
self.covered=True
for k in range(6):
self.carry5+=str(self.showLst[k])+" "
self.carry5+="\n"
self.showResults5.set(self.carry5)
def drawTickets(self):
top=Toplevel()
top.title("Draw Result")
label1=Label(top, text="The wining numbers are ").pack()
var1=StringVar()
label2 = Label(top, textvariable=var1).pack()
var1.set(self.winingNumbers)
var2=StringVar()
Label3 = Label(top, textvariable=var2).pack()
if (self.covered==True):
var2.set("You Win!!")
else:
var2.set("You Lose!!")
lotteryNum()
Print self.usingLst to make sure it contains something, and
self.showResults=Label(frame, text="no choices made")
self.showResults.pack()
then in runLottery
self.showResults["text"]="\n".join(self.usingLst)