Python Tkinter Scrollbar Doesn't Work - python

I've been trying to put scrollbar inside a Canvas that has a LabelFrame and simply some Button inside it, but I can't seems to make the scrollbar works.
Is it possible not to use class, since I'm still new in programming.
Here the code:
def all_alb():
global allAlbum
global all_albwin
global lg
all_albwin = Toplevel()
all_albwin.state('zoomed')
ctr = 0
alb_row = 0
alb_cover = PhotoImage(file="img/placeholder.gif")
scrollbar = Scrollbar(all_albwin)
scrollbar.pack(side=RIGHT, fill=Y)
container = Canvas(all_albwin, yscrollcommand=scrollbar.set, scrollregion=(0,0,1000,1000))
# I do nothing scrollbar-related here
if lg == 1:
btnAdd = Button(container, text="Add New Album", command=add_alb)
btnAdd.grid(row=0)
btnMain = Button(container, text="Back to Main Menu", command=all_albwin.destroy)
btnMain.grid(row=1)
all_frame = LabelFrame(container, text="All Album", padx=10, pady=10)
all_frame.grid(padx=15, pady=15, row=2)
file = open("album/allAlbum.txt", "r")
total = file.readline()
file.close()
if int(total) == 0:
status = Label(all_frame, text="No album found.")
status.grid(row=0)
else:
while ctr < int(total):
file = open("album/alb_info/" + allAlbum[ctr].replace("\n", "") + ".txt", "r")
coverDir = file.readline().replace("\n", "")
coverImg = PhotoImage(file=coverDir)
cover = Button(all_frame, image=coverImg, bd=0, command=lambda ctr=ctr: alb_info(ctr, "all_alb"))
cover.image = coverImg
cover.grid(row=alb_row, column=0, pady=20)
alb_name = Button(all_frame, text=allAlbum[ctr].replace("\n", ""), font = "Helvetica 16 bold", command=lambda ctr=ctr: alb_info(ctr, "all_alb"), bd=0)
alb_name.grid(row=alb_row, column=1, sticky=NW, padx=20, pady=20)
ctr = ctr + 1
alb_row = alb_row + 1
# Scrollbar stuff under here
container.pack(expand=True)
scrollbar.config(command=container.yview)

You cannot scroll an object added to the canvas with grid. You must use create_window to place the labelframe inside the canvas.

Related

Restart script on button press using tkinter

I have a simple script to convert Degree Minute Second to Decimal Degree, using tkinter with a simple GUI. The script waits for the user to click the "Calculate" button before proceeding, to ensure values have been entered in the required 'tk.Entry' fields, then displays the calcuated output.
How would I implement a "Reset" button to allow for another calculation to be run?
I was thinking a while loop for my entire script but don't understand how to implement it.
Apologies for the elementary question, this is my first attempt at using tkinter / GUI, it was much easier to add a re-run while loop to the commandline version of my script.
edit: the "Reset" button currently does nothing, it's just for placement.
# Check python version and import correct tkinter.
import string
import sys
if (sys.version_info.major == 3):
print("Python 3")
import tkinter as tk# for Python 3
else:
print("Python 2")
import Tkinter as tk# for Python 2.7
# Configure tkinter window name, size, colour, columns.
root = tk.Tk()
root.title("CCT")
root.resizable(False, False)
root.attributes("-alpha", 0.95)
root.config(bg = "#F5F5F5")
# Label for top of application.
label_info = tk.Label(root, text="Coordinate Conversion Tool", pady = 5, bg = "#e8e8e8", padx=10)
label_info.grid(row=0, column=0, columnspan=4, sticky = tk.W+tk.E, pady=(0,10))
# Label and entry for degree.
label_d = tk.Label(text="Degree ->", bg = "#F5F5F5")
label_d.grid(row=1, column=0, columnspan=2, sticky = tk.W, padx=(10,0))
entry_d = tk.Entry(root, width=10, bg = "#e8e8e8")
entry_d.grid(row=1, column=2, columnspan=2, sticky = tk.E, padx=(0,10))
# Label and entry for minute.
label_m = tk.Label(text="Minute ->", bg = "#F5F5F5")
label_m.grid(row=2, column=0, columnspan=2, sticky = tk.W, padx=(10,0))
entry_m = tk.Entry(root, width=10, bg = "#e8e8e8")
entry_m.grid(row=2, column=2, columnspan=2, sticky = tk.E, padx=(0,10))
# Label and entry for second.
label_s = tk.Label(text="Second ->", bg = "#F5F5F5")
label_s.grid(row=3, column=0, columnspan=2, sticky = tk.W, padx=(10,0))
entry_s = tk.Entry(root, width=10, bg = "#e8e8e8")
entry_s.grid(row=3, column=2, columnspan=2, sticky = tk.E, padx=(0,10))
# Radiobutton for quadrant selection.
def retrieve():
print(quadrant_var.get())
quadrant_var = tk.StringVar(value = "N")
quad_button_n = tk.Radiobutton(root, text = "N", variable = quadrant_var, value = "N", command = retrieve, pady = 3)
quad_button_n.grid(row=4, column=0)
quad_button_e = tk.Radiobutton(root, text = "E", variable = quadrant_var, value = "E", command = retrieve, pady = 3)
quad_button_e.grid(row=4, column=1)
quad_button_s = tk.Radiobutton(root, text = "S", variable = quadrant_var, value = "S", command = retrieve, pady = 3)
quad_button_s.grid(row=4, column=2)
quad_button_w = tk.Radiobutton(root, text = "W", variable = quadrant_var, value = "W", command = retrieve, pady = 3)
quad_button_w.grid(row=4, column=3)
# Set blank variable for wait_variable
var = tk.IntVar()
# Button for calculating the conversion with wait_variable
calculate = tk.Button(text="Calculate", command=lambda: var.set(1))
calculate.grid(row=5, column=0, columnspan=2, sticky = tk.E+tk.W, padx=10, pady=10)
# Button to reset and allow for another calculation
calculate = tk.Button(text="Reset")
calculate.grid(row=5, column=2, columnspan=2, sticky = tk.E+tk.W, padx=10, pady=10)
# Label with placeohlder output text
label_output = tk.Label(text=" ", borderwidth=2, relief="groove", font="Arial, 12", pady=8)
label_output.grid(row=7, column=0, columnspan=4, sticky = tk.W+tk.E, padx=10)
# Label at the bottom of the application
label_foot = tk.Label(text="Developed by Ryan Seabrook", bg = "#F5F5F5", fg = "#7a7a7a", pady = 1)
label_foot.grid(row=8, column=0, columnspan=4, sticky = tk.W+tk.E)
# Wait for the user to press the calculate button.
calculate.wait_variable(var)
# Information from user input for degree minute second, converted to float for math calculation.
degree = float(entry_d.get())
minute = float(entry_m.get())
second = float(entry_s.get())
# Raw calculated output for DMS to DD.
calculated_dd = (float(degree) + (float(minute)/60) + (float(second)/3600))
# Rounded DD output.
rounded_dd = round(calculated_dd,8)
# Fetch string for final output
rounded_dd_str = str(rounded_dd)
final_output = "output"
selected_quadrant = quadrant_var.get()
# If statement to assign correct quadrant value to output
if selected_quadrant == "W":
final_output = "-" + rounded_dd_str + " " + selected_quadrant
elif selected_quadrant == "S":
final_output = "-" + rounded_dd_str + " " + selected_quadrant
else:
final_output = rounded_dd_str + " " + selected_quadrant
# Label for final output
label_output = tk.Label(text=final_output, borderwidth=2, relief="sunken", font="Arial 12", pady=8)
label_output.grid(row=7, column=0, columnspan=4, sticky = tk.W+tk.E, padx=10)
# Holds python while tkinter root window is open.
root.mainloop()
There seems to be a related post here,
Restart program tkinter
which also links to this code snippet on this page,
https://www.daniweb.com/programming/software-development/code/260268/restart-your-python-program
which may solve your problem.
I hope this helps!

TKinter window not showing in program with .after() statement

I am trying to do a self-updating script to display a table with some data I am scraping from a few websites. The data is scraped, loaded, formatted and then it should be displayed in a table format in TKinter. However, when I make it self-refreshing with root.after() the window does not appear at all. I know the program is running, because I see output in the terminal, but nothing comes up as a TKwindow. Is there something I am missing from .after()'s behaviour? Would it not run when there are a lot of lines?
I tried just commenting the .after() part and the script would execute completely and then show me the window. I also never entered the Else statement, which is fine, but for some reason the code would not work even with just the If statement.
Below is the code I used
root = Tk()
root.geometry("1080x1080")
def calculations():
Scraping_and_writing_in_files()
final_result = File_format_pandas()
if len(final_result.index) == 0:
label = Label(root, text = "There are no hits")
label.pack()
print("I am in the if statement - no hits found")
else:
print("I am in the else statement") # I was never in the Else statement so you can ignore the code below
#Create a main frame
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)
#Create a canvas
my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
#Add scrollbar
my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
#Configure scrollbar
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>',lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))
def _on_mouse_wheel(event):
my_canvas.yview_scroll(-1 * int((event.delta / 120)), "units")
my_canvas.bind_all("<MouseWheel>", _on_mouse_wheel)
#Create another frame in the canvas
second_frame = Frame(my_canvas)
#Add that new frame to a window in the canvas
my_canvas.create_window((0,0), window=second_frame, anchor = "nw")
initial_entries1 = Entry(second_frame,font=("Helvetica", 12),bd=0,width=30)
initial_entries1.insert(0, "Match Name")
initial_entries1.config(state = "readonly")
initial_entries1.grid(row=0, column=0)
initial_entries2 = Entry(second_frame,font=("Helvetica", 12),bd=0,width=30)
initial_entries2.insert(0, "Result for T1")
initial_entries2.config(state = "readonly")
initial_entries2.grid(row=0, column=1)
initial_entries3 = Entry(second_frame,font=("Helvetica", 12),bd=0,width=30)
initial_entries3.insert(0, "Result for Draw")
initial_entries3.config(state = "readonly")
initial_entries3.grid(row=0, column=2)
initial_entries3 = Entry(second_frame,font=("Helvetica", 12),bd=0,width=30)
initial_entries3.insert(0, "Result for T2")
initial_entries3.config(state = "readonly")
initial_entries3.grid(row=0, column=3)
for thing in range(len(final_result.index)):
match_name = Entry(second_frame, font=("Helvetica", 10),bd=0,width=30)
match_name.insert(0, final_result['Match name'].iloc[thing])
match_name.config(state = "readonly")
match_name.grid(row=thing+1, column=0)
result_t1 = Entry(second_frame, font=("Helvetica", 10),bd=0,width=15)
result_t1.insert(0, final_result['Difference Team 1 For'].iloc[thing])
if float(final_result['Difference Team 1 For'].iloc[thing]) > 0:
result_t1.config(state = "readonly")
result_t1.grid(row=thing+1, column=1)
result_t2 = Entry(second_frame, font=("helvetica", 10), bd=0, width=15)
result_t2.insert(0, final_result['Difference Team 2 For'].iloc[thing])
if float(final_result['Difference Team 2 For'].iloc[thing])>0:
result_t2.config(state = "readonly")
result_t2.grid(row=thing+1, column=3)
result_draw = Entry(second_frame, font=("helvetica", 10), bd=0, width=15)
result_draw.insert(0, final_result['Difference Draw For'].iloc[thing])
if float(final_result['Difference Draw For'].iloc[thing]) > 0:
result_draw.config(state = "readonly")
result_draw.grid(row=thing+1, column=2)
root.after(2000, main_frame.destroy())
# label1 = Label(second_frame, text="Google Hyperlink", fg="blue", cursor="hand2")
# label1.pack()
# label1.bind("<Button-1>", lambda e: callback("http://www.google.com"))
root.after(1000, calculations())
calculations()
root.mainloop()
In the after method no parentheses are needed, since they call the function immediately and will use whatever it returns as callback after the delay. Thank you Jasonharper and Sujay.
root.after(1000, calculations()) => should be root.after(1000, calculations)

Tkinter Text widget returns ".!frame3.!frame3.!frame.!text" instead of appropriate values

I'm currently working on a project where you scan bar codes and it implements the result into an excel file. I am using tkinter to make my GUI, however, when I try to get the values from a text widget it returns the value ".!frame3.!frame3.!frame.!text". how can I fix this to get the appropriate values?
here is my code so far
import tkinter as tk
from tkinter import *
root = tk.Tk(className = "Tool Manager")
root.configure(bg='#C4C4C4')
root.title('Main Screen')
root.geometry("800x600")
main = Frame(root, bg='#C4C4C4', width = 800, height = 600)
#This is the contents of the Main Frame (screen 1)
frame_pad1 = Frame(main, bg='#C4C4C4')
frame_1 = Frame(main,bg='#C4C4C4')
frame_2 = Frame(main, bg='#C4C4C4')
frame_3 = Frame(main, bg='#C4C4C4')
min = Frame(root, bg = 'GREEN')
#mout stuffs
mout = Frame(root, bg = '#C4C4C4')
outframe_pad1 = Frame(mout, bg='#C4C4C4')
outframe_1 = Frame(mout, bg='#C4C4C4')
outframe_2 = Frame(mout, bg='#C4C4C4')
outframe_3 = Frame(mout, bg='#C4C4C4')
#code for changing screens
def raise_frame(frame):
frame.tkraise()
for frame in (main, min, mout):
frame.grid(row=1, column=1, sticky='news')
#sets frame weight for 3 rows (centers frames)
rows = 0
while rows < 3:
root.rowconfigure(rows, weight=1)
root.columnconfigure(rows,weight=1)
rows += 1
def commit_to_file():
ID = name.get()
out_list.get('1.0', 'end-1c')
print(out_list) #<----- THIS IS WHERE I'M RETURNING VALUES TO THE TERMINAL
def on_every_keyboard_input(event):
update_char_length(out_list)
#updating Line Length Information
def update_char_length(out_list):
string_in_text = out_list.get('1.0', '1.0 lineend')
string_length = len(string_in_text)
print(string_length)
if (string_length == 4):
out_list.insert(0.0, '\n')
out_list.mark_set("insert", "%d.%d" % (0,0))
#main screen formatting
area = PhotoImage(file="test.png")
areaLabel = Label(frame_1, image=area, bg='#C4C4C4')
areaLabel.pack(side=RIGHT)
mwLabel = Label(frame_2,text="this is only a test", font=("Airel", 20), bg='#C4C4C4')
mwLabel.pack(side=RIGHT)
out_button = Button(frame_3, text="Check Out", command=lambda:raise_frame(mout) , height=5, width=20, font=("Airel", 15))
out_button.pack(side=RIGHT, padx=20, pady = 4)
in_button = Button(frame_3, text="Check In", command=lambda:raise_frame(min), height=5, width=20, font=("Airel", 15))
in_button.pack(side=LEFT, padx=20, pady = 4)
#out screen formatting
name = Entry(outframe_1, font=("Airel", 15))
name.pack(side=RIGHT)
name_lbl = Label(outframe_1, text="ID Number", bg='#C4C4C4', font=("Airel", 15))
name_lbl.pack(side=LEFT)
outlist = Frame(outframe_2, bd=1, relief=SUNKEN)
outlist.pack(side=LEFT)
out_list = Text(outlist, height=30, width=40)
out_list.pack(side=RIGHT)
done_btn = Button(outframe_3, text="Done", command=commit_to_file, font=("Ariel", 15))
done_btn.pack(side=RIGHT, padx=20, pady=4)
#init to main screen
raise_frame(main)
#drawing objects for main screen
frame_pad1.pack(padx=1, pady=25)
frame_1.pack(padx=1,pady=1)
frame_2.pack(padx=10,pady=1)
frame_3.pack(padx=1, pady=80)
#drawing out screen
outframe_1.pack(padx=1, pady=1)
outframe_2.pack(padx=1,pady=1)
outframe_3.pack(padx=1, pady=1)
#calls line info update out screen
out_list.bind('<KeyRelease>', on_every_keyboard_input)
root.mainloop()
You are printing the command and not the value of it. Put the command in a variable and then print the variable.
Example: myVar = out_list.get("1.0", "end-1c") and then print(myVar)

Python Tkinter Scrollbar Shaky Scrolling

Introduction: My Python Tkinter application is designed to have a scrollbar on the side so that if the window is resized, the application can still be viewed via the scrollbar. I do this by putting a frame with all my content inside a canvas, with a scrollbar controlling the canvas. On window resize, I have a function called resizeCanvas which resizes the canvas.
Problem: After I resize the window, the scrollbar sort of works but it seems to jump around and fidget like its having a seizure. However, at initialization the scroll bar works smoothly. So resizing the window seems to be the problem. Any suggestions on why the scroll bar is behaving like this?
Application Hierarchy:
Tkinter root
frame (just a container for the canvas)
canvas (scroll bar is attached to this canvas)
frame (content is in this frame)
NOTE: Python 2.7.2
Code Snippit:
myframe=Frame(root,width=winx,height=winy)
myframe.place(x=0,y=0)
canvas = Tkinter.Canvas(myframe,width=winx,height=winy)
frame = Frame(canvas,width=winx,height=winy)
myscrollbar=Scrollbar(myframe,orient="vertical")
myscrollbar.configure(command=canvas.yview)
canvas.configure(yscrollcommand=myscrollbar.set)
myscrollbar.pack(side="left",fill="y")
canvas.pack(side="left")
canvas.create_window((0,0),window=frame,anchor='nw')
frame.bind("<Configure>", initializeCanvas)
bind("<Configure>", resizeCanvas)
def initializeCanvas(self, event):
canvas.configure(scrollregion=self.canvas.bbox("all"),width=winx,height=winy)
def resizeCanvas(self, event):
update()
cwidth = self.winfo_width()
cheight = self.winfo_height()
canvas.config(width=cwidth, height=cheight)
Entire Code:
import sys
#external python files are in the includes folder
sys.path.insert(0, 'includes')
import webbrowser
import os
import Tkinter
import tkFileDialog
import tkMessageBox
import ConfigParser
from ttk import *
import tkFont
import Tix
# configurations held in this variable
config = ConfigParser.RawConfigParser()
# pady padding for create buttons
py = 15
# padx padding for create buttons
px = 5
# padding on left side for indenting elements
indentx = 25
winx = 815
winy = 515
# array to hold features
FEATURES =['']
# wrapper class for GUI
class AppTk(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.parent = parent
self.settings = "./settings/settings.cfg"
self.initialize_gui()
self.minsize(winx, 100)
sizex = winx
sizey = winy
posx = 100
posy = 100
self.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
try:
self.iconbitmap('./imgs/favicon.ico')
except Exception, e:
print "\n****Error occurred (GUI_MBD_File_Creator.init): favicon not found!"
# Setup grid of elements in GUI
# action: on start of application
def initialize_gui(self):
# ----------------------------------------------------
# START Settings frame initialization
# ----------------------------------------------------
self.myframe=Frame(self,width=winx,height=winy)
self.myframe.place(x=0,y=0)
self.canvas = Tkinter.Canvas(self.myframe,width=winx,height=winy)
self.frame = Frame(self.canvas,width=winx,height=winy)
self.myscrollbar=Scrollbar(self.myframe,orient="vertical")
self.myscrollbar.configure(command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.myscrollbar.set)
self.myscrollbar.pack(side="left",fill="y")
self.canvas.pack(side="left")
self.canvas.create_window((0,0),window=self.frame,anchor='nw')
self.frame.bind("<Configure>",self.initializeCanvas)
self.bind("<Configure>",self.resizeCanvas)
frameFont = tkFont.Font(size=13, weight=tkFont.BOLD)
self.frameSettings = Tkinter.LabelFrame(self.frame, text="Settings: fill these out first", relief="groove", borderwidth="3", font=frameFont)
self.frameSettings.grid(sticky="EW", padx=px, pady=(5,15))
labelSpreadsheet = Label(self.frameSettings, text="1. Spreadsheet Path:")
labelSpreadsheet.grid(row=0, column=0, sticky='W', padx=(indentx,0))
variableSpreadsheet = Tkinter.StringVar()
self.entrySpreadsheet = Entry(self.frameSettings, textvariable=variableSpreadsheet, width=90, state=Tkinter.DISABLED)
self.entrySpreadsheet.grid(row=0, column=1, sticky='W', padx=px, pady=5)
self.entrySpreadsheet.svar = variableSpreadsheet
buttonSpreadsheet = Button(self.frameSettings, text="Browse...")
buttonSpreadsheet.grid(row=0, column=2, sticky='W', padx=(0,10))
labelPath = Label(self.frameSettings, text="2. Root Save Path:")
labelPath.grid(row=1, column=0, sticky='W', padx=(indentx,0))
variablePath = Tkinter.StringVar()
self.entryPath = Entry(self.frameSettings, textvariable=variablePath, width=90, state=Tkinter.DISABLED)
self.entryPath.grid(row=1, column=1, sticky='W', padx=px, pady=(5,10))
self.entryPath.svar = variablePath
buttonPath = Button(self.frameSettings, text="Browse...")
buttonPath.grid(row=1, column=2, sticky='W', padx=(0,10), pady=(0,5))
# ----------------------------------------------------
# START Creation Menu frame initialization
# ----------------------------------------------------
self.frameCreationIndividual = Tkinter.LabelFrame(self.frame, text="Feature Files Creation Menu", relief="groove", borderwidth="3", font=frameFont)
self.frameCreationIndividual.grid(sticky="EW", padx=px, pady=(5,15))
labelReq = Label(self.frameCreationIndividual, text="3. Feature(s):")
labelReq.grid(row=0, column=0, sticky='NW', pady=(5,0), padx=(indentx,15))
self.scrollbarReq = Scrollbar(self.frameCreationIndividual)
self.scrollbarReq.grid(row=1, column=3, rowspan=16, sticky="NSW", pady=(0,15),padx=(0,20))
variableSelectAll = Tkinter.IntVar()
self.checkSelectAll = Checkbutton(self.frameCreationIndividual, text = "Select All", variable = variableSelectAll, onvalue = 1, offvalue = 0)
self.checkSelectAll.grid(row=0, column=1, columnspan=2, sticky='NE', padx=px, pady=(5,0))
self.checkSelectAll.svar = variableSelectAll
labelReq = Label(self.frameCreationIndividual, text="4. Files:")
labelReq.grid(row=0, column=5, sticky='NW', pady=(5,0), padx=15)
variableIndividualFFS = Tkinter.IntVar()
self.checkIndividualFFS = Checkbutton(self.frameCreationIndividual, text = "Create Feature File", variable = variableIndividualFFS, onvalue = 1, offvalue = 0)
self.checkIndividualFFS.grid(row=1, column=5, sticky='NW', padx=15)
self.checkIndividualFFS.svar = variableIndividualFFS
variableIndividualSFS = Tkinter.IntVar()
self.checkIndividualSFS = Checkbutton(self.frameCreationIndividual, text = "Create SubFeature Files", variable = variableIndividualSFS, onvalue = 1, offvalue = 0)
self.checkIndividualSFS.grid(row=2, column=5, sticky='NW', padx=15)
self.checkIndividualSFS.svar = variableIndividualSFS
variableIndividualDO = Tkinter.IntVar()
self.checkIndividualDO = Checkbutton(self.frameCreationIndividual, text = "Create Doc Outline", variable = variableIndividualDO, onvalue = 1, offvalue = 0)
self.checkIndividualDO.grid(row=3, column=5, sticky='NW', padx=15)
self.checkIndividualDO.svar = variableIndividualDO
variableIndividualDWR = Tkinter.IntVar()
self.checkIndividualDWR = Checkbutton(self.frameCreationIndividual, text = "Create Doc With Requirements", variable = variableIndividualDWR, onvalue = 1, offvalue = 0)
self.checkIndividualDWR.grid(row=4, column=5, sticky='NW', padx=(15,30))
self.checkIndividualDWR.svar = variableIndividualDWR
self.buttonIndividualAll = Button(self.frameCreationIndividual, text="Create...", width=43)
self.buttonIndividualAll.grid(row=1, column=6, rowspan=4, sticky='NESW', padx=px)
# ----------------------------------------------------
# START Entire System Creation frame initialization
# ----------------------------------------------------
self.frameCreationSystem = Tkinter.LabelFrame(self.frame, text="System Creation Menu", relief="groove", borderwidth="3", font=frameFont)
self.frameCreationSystem.grid(sticky="EW", padx=px, pady=15)
self.buttonLAIF = Button(self.frameCreationSystem, text="Create Layers/App Integration Files", width=35)
self.buttonLAIF.grid(row=11, column=0, sticky='NESW', ipady=5, padx=(indentx,0), pady=(16,8))
self.buttonDO = Button(self.frameCreationSystem, text="Create Entire Doc Outline")
self.buttonDO.grid(row=12, column=0, sticky='NESW', ipady=5, padx=(indentx,0), pady=(8,10))
# ----------------------------------------------------
# START Feature Tab Creation Frame initialization
# ----------------------------------------------------
self.frameCreationNew = Tkinter.LabelFrame(self.frame, text="Feature Tab Creation Menu", relief="groove", borderwidth="3", font=frameFont)
self.frameCreationNew.grid(sticky="EW", padx=px, pady=(15,5))
labelIssueSpreadsheet = Label(self.frameCreationNew, text="2. Feature Spreadsheet Path:")
labelIssueSpreadsheet.grid(row=0, column=0, sticky='W', padx=(indentx,0))
variableIssueSpreadsheet = Tkinter.StringVar()
self.entryIssueSpreadsheet = Entry(self.frameCreationNew, textvariable=variableIssueSpreadsheet, width=83, state=Tkinter.DISABLED)
self.entryIssueSpreadsheet.grid(row=0, column=1, sticky='W', padx=px, pady=5)
self.entryIssueSpreadsheet.svar = variableIssueSpreadsheet
buttonIssueSpreadsheet = Button(self.frameCreationNew, text="Browse...")
buttonIssueSpreadsheet.grid(row=0, column=2, sticky='W')
labelFeatureTab = Label(self.frameCreationNew, text="3. Feature Name:")
labelFeatureTab.grid(row=1, column=0, sticky='W', padx=(indentx,0))
variableFeatureTab = Tkinter.StringVar()
self.entryFeatureTab = Entry(self.frameCreationNew, textvariable=variableFeatureTab, width=83)
self.entryFeatureTab.grid(row=1, column=1, sticky='W', padx=px, pady=5)
self.entryFeatureTab.svar = variableFeatureTab
labelFeatureAbbrv = Label(self.frameCreationNew, text="4. Feature Abbreviation:")
labelFeatureAbbrv.grid(row=2, column=0, sticky='W', padx=(indentx,0))
variableFeatureAbbrv = Tkinter.StringVar()
self.entryFeatureAbbrv = Entry(self.frameCreationNew, textvariable=variableFeatureAbbrv, width=83)
self.entryFeatureAbbrv.grid(row=2, column=1, sticky='W', padx=px, pady=5)
self.entryFeatureAbbrv.svar = variableFeatureAbbrv
self.buttonNewFeature = Button(self.frameCreationNew, text="Create Feature Tab", width=35)
self.buttonNewFeature.grid(row=3, column=0, columnspan =2, sticky='NWS', ipady=5, pady=(8,10), padx=(indentx,0))
# ----------------------------------------------------
# START general purpose methods
# ----------------------------------------------------
def initializeCanvas(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"),width=winx,height=winy)
def resizeCanvas(self, event):
self.update()
cwidth = self.winfo_width()
cheight = self.winfo_height()
self.canvas.config(scrollregion=self.canvas.bbox("all"), width=cwidth, height=cheight)
# ----------------------------------------------------
# Initialize application
# ----------------------------------------------------
if __name__ == "__main__":
app = AppTk(None)
app.title("MBD File Creator")
app.mainloop()
While there may be other errors, you have one very critical flaw: you are creating a binding for the <Configure> event to self. Because self is the instance of the root window, every widget you create inherits this binding. Your resizeCanvas method is literally being called hundreds of times at startup, and hundreds of times when the window is resized.
You also have the problem where you are calling update in an event handler. As a general rule, this is bad. In effect, it's like calling mainloop in that it will not return until all events are processed. If your code causes more events to be processed (such as reconfiguring a window and causing the <configure> event to fire, you end up in a recursive loop.
You probably need to remove the calls to self.update() and/or replace them with the less dangerous self.update_idletasks(). You also need to either remove the <Configure> binding on self, or in the method you need to check for which widget caused the event to fire (ie: check that the event.widget is the root window).
Try first to save the canvas.create_window to a variable as following:
self.windows_item = canvas.create_window((0,0),window=frame,anchor='nw')
then at the end of resizeCanvas to call the following method:
def update(self):
"Update the canvas and the scrollregion"
self.update_idletasks()
canvas.config(scrollregion=canvas.bbox(self.windows_item))
Hope it helps!
Most of it found here: https://stackoverflow.com/a/47985165/2160507

How to get tkinter Spinbox's value?

I am trying to make a timer on python Tkinter. To set the timer, I am using spinboxes. But, I am having trouble getting the value of my spinboxes to be turned into the variables time_h, time_m and time_s.
I have tried .get() but it is not working. When I tried printing the variables I got NameError: name 'spin_h' is not defined.
from tkinter import *
window = Tk()
window.title("Timer")
window.geometry('350x200')
hour = 0
minute = 0
second = 0
timer = (str(hour) + ':' + str(minute) + ':' + str(second))
lbl = Label(window, text=timer, font=("Arial Bold", 50))
hour_s = 0
min_s = 0
sec_s = 0
def save_time():
time_h = spin_h.get()
time_m = spin_m.get()
time_s = spin_s.get()
def new_window():
set_time = Tk()
spin_h = Spinbox(set_time, from_=0, to=10, width=5)
spin_h.grid(column=1,row=0)
spin_m = Spinbox(set_time, from_=0, to=60, width=5)
spin_m.grid(column=3,row=0)
spin_s = Spinbox(set_time, from_=0, to=60, width=5)
spin_s.grid(column=5,row=0)
h_label = Label(set_time, text='h', font=("Arial Bold", 10))
h_label.grid(column=2, row=0)
m_label = Label(set_time, text='m', font=("Arial Bold", 10))
m_label.grid(column=4, row=0)
s_label = Label(set_time, text='s', font=("Arial Bold", 10))
s_label.grid(column=6, row=0)
set_button = Button(set_time, text="Set Time", command=save_time)
set_button.grid(column=3, row=2)
btn = Button(window, text="Set Time", command=new_window)
btn.grid(column=3, row=2)
lbl.grid(column=3, row=0)
window.mainloop()
spin_h is a variable local to the new_window() function and there cannot be accessed by the save_time() function. You could declare it a global variable at the beginning of new_window() to fix that. - #Martineau (just made it into an answer instead of a comment).
Thanks Martineau

Categories

Resources