Tkinter Scrollable Text, the slider doesn't appear - python

I'm try to create scroll bar in "notepad(Program name)" but when i run my program it don't show
scrollbar in window .......................................................................
.....................................................................
from tkinter import *
SIDE_R = RIGHT
windows = Tk()
windows.title("NotePad")
windows.minsize(width=60, height=80)
windows.config()
frame = Frame(windows)
# Menu bar
# # File
menubar = Menu(windows)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="close")
file.add_separator()
file.add_command(label="Exit", command=windows.quit)
menubar.add_cascade(label="File", menu=file)
# # Edit
edit = Menu(menubar, tearoff=0)
edit.add_separator()
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Cute")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
# # Help
helps = Menu(menubar, tearoff=0)
helps.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
# Create place to write a text
text = Text(windows)
text.focus()
text.grid(pady=0.5, padx=10)
# Creating Scale
scroll = Scrollbar(windows, orient=VERTICAL,)
scroll.grid(row=0, column=1, sticky=NS+SE)
text.config(yscrollcommand=scroll.set)
scroll.config(command=text.yview)
windows.config(menu=menubar)
windows.mainloop()

Related

Font changing menu buttons don't switch the font in tkinter text editor

First post here, I'm working on a very basic text editor as a beginner project in python and I've managed to get a big chunk of it working, but I just can't figure out how to make the font and font sizing menu buttons work. At first, I just had one button that switched the text to Times New Roman with a size of 12 instead of the default Tkinter font, and that worked, but when I added in the capability to change the font and font size independently it would just default to Calibri size 12 (which are both the last buttons added in the code), and I couldn't change the font or sizing. Any ideas?
Problem Code:
def change_font(fontname):
global font
font = fontname
text_info.configure(font=(font, font_size))
def change_font_size(size):
global font_size
font_size = size
text_info.configure(font=(font, font_size))
font_menu = Menu(menubar, tearoff=0)
font_menu.add_command(label="Times New Roman", command=change_font("Times New Roman"))
font_menu.add_command(label="Calibri", command=change_font("Calibri"))
menubar.add_cascade(label="Font", menu=font_menu)
font_size_menu = Menu(menubar, tearoff=0)
for i in range(8, 13):
font_size_menu.add_command(label=str(i), command=change_font_size(i))
menubar.add_cascade(label="Font Size", menu=font_size_menu)
Full Code:
from tkinter import *
def text_opener():
try:
f = open(text_name, "r+")
except FileNotFoundError:
f = open(text_name, "a+")
f.close()
f = open(text_name, "r+")
return f
text_name = input("What is the name of your .txt file? ") + ".txt"
text = text_opener()
root = Tk()
# intended default font and font size
font = "Arial"
font_size = 11
root.title("Text Editor")
root.geometry("640x360")
root.resizable(width=False, height=False)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text_info = Text(root, yscrollcommand=scrollbar.set, wrap=WORD)
scrollbar.config(command=text_info.yview)
text_info.pack(fill=BOTH)
text_info.insert(INSERT, text.read())
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
def save():
text.seek(0)
text.write(text_info.get("1.0", 'end-1c'))
text.truncate()
filemenu.add_command(label="Save", command=save)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
# problem code below
def change_font(fontname):
global font
font = fontname
text_info.configure(font=(font, font_size))
def change_font_size(size):
global font_size
font_size = size
text_info.configure(font=(font, font_size))
font_menu = Menu(menubar, tearoff=0)
font_menu.add_command(label="Times New Roman", command=change_font("Times New Roman"))
font_menu.add_command(label="Calibri", command=change_font("Calibri"))
menubar.add_cascade(label="Font", menu=font_menu)
font_size_menu = Menu(menubar, tearoff=0)
for i in range(8, 13):
font_size_menu.add_command(label=str(i), command=change_font_size(i))
menubar.add_cascade(label="Font Size", menu=font_size_menu)
root.config(menu=menubar)
root.lift()
root.attributes('-topmost', True)
root.after_idle(root.attributes, '-topmost', False)
root.mainloop()
text.close()
To pass an argument into a command you have to use a lambda function or a partial object or similar.
font_menu.add_command(label="Times New Roman", command=lambda: change_font("Times New Roman"))

How do you make a drop down menu in Tkinter?

I have a quick question, how would you make a drop down menu in Tkinter like the one below:
This menu has a drop down option, how would you add a drop down in tkinter here is my code:
# Menu Bar
MenuBar = Menu(root)
root.config(menu=MenuBar)
MenuBar.config(bg="White", fg="Black", activebackground="Whitesmoke", activeforeground="Black", activeborderwidth=1, font=('Monaco', 11))
# Settings Option
SettingsOption = Menu(MenuBar, tearoff=False)
MenuBar.add_cascade(label="Settings", menu=SettingsOption)
SettingsOption.add_command(label="Help", command=None)
SettingsOption.add_command(label="Documentation", command=None)
So whenever I click Settings I should get a menu called help. Then when I hover over help I should get another dropdown menu called documentation. How would you do this in Python Tkinter?
You can use add_cascade() to add sub-menu:
import tkinter as tk
root = tk.Tk()
menubar = tk.Menu(root)
menubar.config(bg="white", fg="black", activebackground="whitesmoke", activeforeground="black", activeborderwidth=1, font="Monaco 11")
settings_menu = tk.Menu(menubar, tearoff=False)
help_menu = tk.Menu(settings_menu, tearoff=False)
help_menu.add_command(label="Documentation")
settings_menu.add_cascade(label="Help", menu=help_menu)
menubar.add_cascade(label="Settings", menu=settings_menu)
root.config(menu=menubar)
root.mainloop()

why giving a tab master window and adding it to tk.notebook() result as the tab was given notebook as a master window

I'm currently a noob to tkinter as i made this code. so kindly ignore any foolishness if found.
import tkinter as tk
from tkinter import ttk
from tkinter import Menu
win=tk.Tk()
win.title('Tabs GUI')
tab_control=ttk.Notebook(win)
tab1=ttk.Frame(tab_control)
tab_control.add(tab1,text='Tab 1')
tab_control.grid()
tab2=ttk.Frame(win) #1
tab_control.add(tab2,text='Tab 2')
menuBar = Menu(tab1) #2
win.config(menu=menuBar)
# Add menu items
fileMenu = Menu(menuBar, tearoff=0)
fileMenu.add_command(label="New")
fileMenu.add_separator()
fileMenu.add_command(label="Exit")
menuBar.add_cascade(label="File", menu=fileMenu)
# Add another Menu to the Menu Bar and an item
helpMenu = Menu(menuBar, tearoff=0)
helpMenu.add_command(label="About")
menuBar.add_cascade(label="Help", menu=helpMenu)
ttk.Label(tab2, text="Choose a number:").grid(column=0, row=0)
numberChosen = ttk.Combobox(tab2, width=8)
numberChosen['values'] = (1, 2, 4, 42, 100)
numberChosen.grid(column=0, row=1)
numberChosen.current(0)
chVarDis = tk.IntVar()
check1 = tk.Checkbutton(tab2, text="Disabled", variable=chVarDis, state='disabled')
check1.select()
check1.grid(column=0, row=2, sticky=tk.W)
chVarUn = tk.IntVar()
check2 = tk.Checkbutton(tab2, text="UnChecked", variable=chVarUn)
check2.deselect()
check2.grid(column=1, row=2, sticky=tk.W )
win.mainloop()
now the first problem is that on #1 i gave 'tab2' master window i.e 'win', then added it to the notebook but it acts like i gave it notebook() as a master window because 'tab1' and 'tab2' are functioning same. And the second problem is why 'combobox' is auto-focused when i open 'tab2'. and the same goes for Menu() #2, i've given it parent tab1 yet it is displayed in top level window win

How to get tkinter menubar label Value?

I have looked a lot but can`t find the answer, below is an example:
Menu.add_command(label='abc',command=callback)
How can I get this 'abc' for variable?
You can use entrycget() and pass to it the "label" option.
Here is a short example to demonstrate how it works:
import tkinter as tk
def callback(menu):
x= menu.entrycget(0, "label")
print(x) # This will print "abc" in your Terminal
root = tk.Tk()
menu_bar = tk.Menu(root)
file_menu = tk.Menu(menu_bar, tearoff=False)
file_menu.add_command(label="abc", command=lambda: callback(file_menu))
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()
I solved ur problem. Try this:
from tkinter import *
def callback(menu):
for index in range(0,1): print( menu.entrycget(0, "label"))
def callback1(menu1):
for index in range(1, 2): print( menu1.entrycget(1, "label"))
def callback2(menu):
for index in range(2,3): print( menu.entrycget(2, "label"))
def callback3(menu):
for index in range(3,4): print( menu.entrycget(3, "label"))
def callback4(menu):
for index in range(4,4): print( menu.entrycget(4, "label"))
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=lambda: callback(filemenu))
filemenu.add_command(label="Open", command=lambda: callback1(filemenu))
filemenu.add_command(label="Save", command=lambda: callback2(filemenu))
filemenu.add_command(label="Save as...", command=lambda: callback3(filemenu))
filemenu.add_command(label="Close", command=None)
root.config(menu=menubar)
root.mainloop()

Using .get() within tkinter ScrolledFrame

I am trying to achieve grabbing par02_1 using .get(). I have success writing the rest of the .txt file but my program is not grabbing my gui entry lines. I'm guessing this has something to do with the association self, and the scrollable section, etc. but I can't track this one down. Any help is appreciated.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import time
root = Tk()
# GUI Window
root.title("Outfile Automation")
# Gui Future Menu Logic
def future01():
print("Future Command 01")
# GUI Main Menu
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Script...", command=future01)
subMenu.add_separator()
subMenu.add_command(label="Exit Program", command=future01)
helpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpMenu, command=future01)
helpMenu.add_command(label="Instruction Manual", command=future01)
helpMenu.add_command(label="Software Version: A0.003")
##Scrollbar
class VerticalScrolledFrame(Frame):
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
if __name__ == "__main__":
class AutoApp(Tk):
def __init__(self, *args, **kwargs):
root = Tk.__init__(self, *args, **kwargs)
self.frame = VerticalScrolledFrame(root)
self.frame.pack()
self.label = Label(text="")
self.label.pack()
self.par02_1 = StringVar()
title_1 = Label(self.frame.interior, text="Device IP (DHCP)", fg="blue", font="Verdana 10 underline")
title_1.pack()
label_1 = Label(self.frame.interior, text="Device 01")
label_1.pack()
entry_1 = Entry(self.frame.interior, textvariable=self.par02_1)
entry_1.pack()
outFile = open('CSC.txt', 'wt')
outFile.write("[Script Header]\nDebugStrings=on\nAbortOnError=on\nConcurrentSectionLimit=230\n"
"//23 Devices if necessary""\n\n[Variables]""\n"
+ (self.par02_1.get()) + "\n\n"
"[Device01]\nConnect=tcp |proc01|\nRunAsSingleTransaction=on\nEthernetDHCPHost "
+ (self.par02_1.get()) + "EthernetCurrentConnectionInfo\n")
outFile.close()
def muser():
feedback_1 = Label(root, text="Creating Script...").pack()
feedback_2 = Label(root, text="Script Complete!").pack()
time.sleep(2)
return
# GUI Buttons
mbutton = Button(root, text="Create Script", command=muser, fg="black", bg='green')
mbutton.pack()
app = AutoApp()
app.mainloop()
Hello thank you both for your guidance as I learn proper syntax. I have a long way to go but you both helped point me in the right direction so I can get my program online. I stripped this down to the basics and will implement a variation of the following architecture in my actual code.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import time
root = Tk()
# GUI Window
root.title("Outfile Automation")
# Gui Future Menu Logic
def future01():
print("Future Command 01")
# GUI Main Menu
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Script...", command=future01)
subMenu.add_separator()
subMenu.add_command(label="Exit Program", command=future01)
helpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpMenu, command=future01)
helpMenu.add_command(label="Instruction Manual", command=future01)
helpMenu.add_command(label="Software Version: A0.003")
par02_1 = StringVar()
title_1 = Label(root, text="Device IP (DHCP)", fg="blue", font="Verdana 10 underline")
title_1.pack()
label_1 = Label(root, text="Device 01")
label_1.pack()
entry_1 = Entry(root, textvariable=par02_1)
entry_1.pack()
root.mainloop()
template = """[Script Header]\nDebugStrings=on\nAbortOnError=on\nConcurrentSectionLimit=230\n//23 Devices if necessary
\n\n[Variables]\n{}\n\n[Device01]\nConnect=tcp |proc01|\nRunAsSingleTransaction=on\nEthernetDHCPHost\nEthernetCurrentConnectionInfo\n"""
outFile = open('CSC.txt', 'wt')
outFile.write(template.format(par02_1.get()).rstrip())
outFile.close()
root.mainloop()

Categories

Resources