Related
I am creating Vocabulary, a GUI program to manage unknown words. I am getting:
/usr/bin/python3.5 /home/cali/PycharmProjects/Vocabulary/Vocabulary.py
Exception in Tkinter callback Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/init.py", line 1553, in call
return self.func(*args) File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 86, in
add_item
self.listBox.insert(END, self.get_word()) AttributeError: 'Vocabulary' object has no attribute 'listBox'
Process finished with exit code 0
... when I try to add an item to the listbox.
Here is what I have done:
#!/usr/bin/env python
# Vocabulary.py
# GUI program to manage unknown words
from tkinter import *
class Word:
def __init__(self, wordorphrase, explanation, translation, example):
self.wordorphrase = wordorphrase
self.explanation = explanation
self.translation = translation
self.example = example
class Vocabulary(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
self.master.resizable(width = False, height = False)
self.master.title("Vocabulary")
self.create_widgets()
def create_widgets(self):
lblWordsOrPhrases = Label(self.master, text = 'Words or Phrases:')
lblWordsOrPhrases.grid(row = 0, column = 0)
lblWordOrPhrase = Label(self.master, text = 'Word or phrase:')
lblWordOrPhrase.grid(row = 0, column = 1, sticky = W)
listBox = Listbox(self.master,
height = 34,
width = 30)
listBox.grid(row = 1, column = 0, rowspan = 7)
txt_WordOrPhrase = Text(self.master,
height = 1,
width = 40)
txt_WordOrPhrase.grid(row = 1, column = 1, sticky = N)
lblExplanation = Label(self.master, text = 'Explanation:')
lblExplanation.grid(row = 2, column = 1, sticky = W)
txt_Explanation = Text(self.master,
height = 10,
width = 40)
txt_Explanation.grid(row = 3, column = 1, sticky = N)
lblTranslation = Label(self.master, text = 'Translation:')
lblTranslation.grid(row = 4, column = 1, sticky = W)
txt_Explanation = Text(self.master,
height = 10,
width = 40)
txt_Explanation.grid(row = 5, column = 1, sticky = N)
lblExamples = Label(self.master, text = 'Example(s):')
lblExamples.grid(row = 6, column = 1, sticky = W)
txt_Explanation = Text(self.master,
height = 10,
width = 40)
txt_Explanation.grid(row = 7, column = 1, sticky = S)
btn_Add = Button(self.master,
text = 'Add',
command = self.add_item)
btn_Add.grid(row = 8, column = 0, sticky = W)
def get_word(self):
return self.txt_WordOrPhrase.get('1.0', '1.0 lineend')
def get_explanation(self):
return self.txt_Explanation.get('1.0', '1.0 lineend')
def get_translation(self):
return self.txt_Translation.get('1.0', '1.0 lineend')
def get_example(self):
return self.txt_Example.get('1.0', '1.0 lineend')
def add_item(self):
self.listBox.insert(END, self.get_word())
def main():
root = Tk()
Vocabulary(root)
root.mainloop()
if __name__ == '__main__':
main()
I'm using Python 3.5.
You listbox is a variable local to create_widgets since it is not set with self. In order to make the variable available instance-wide, you need to contain it in self.
Change the line in create_widgets to self.listBox = Listbox(self.master, height = 34, width = 30) and change every reference to listBox to self.listBox in order to apply this change.
You might want to defined self.listBox in __init__(), as it might help keep track of instance variables.
This script when run, opens a window that is divided into 3 frames:
A big frame into which data will be shown (label widgets).
A smaller frame underneath it with user input widgets.
A small frame in the bottom-right corner with a textbox widget.
The big frame will have a lot of data (= label-widgets) so I need it to be scrollable (vertically).
This I have done by creating a canvas widget alonside a scrollbar widget. In the canvas, a frame widget is placed.
Everything seems to be working, however my resizing function does not.
My frame widget does not get its dimensions updated! This is probably because of an error that I can't manage to fix.
Fundamental question:
The script gives an error on the "lambda: resize_frame(self)" command on line 43. How do i fix this?
Side-note: My issue probably has more to do with an improper binding on the canvas widget. Because I'm not sure I wanted to give enough context (script).
Many thanks in advance.
from Tkinter import *
import math
class Processing(Toplevel):
def __init__(self, master, *args, **kwargs):
Toplevel.__init__(self, master)
self.master = master
self.title("Process Window")
for r in range(6):
self.rowconfigure(r, weight = 1)
for c in range(4):
self.columnconfigure(c, weight = 1)
### WINDOW size and position definitions ###
ScreenSizeX = master.winfo_screenwidth()
ScreenSizeY = ( master.winfo_screenheight() - 75 ) #about 75pixels for taskbar on bottom of screen (Windows)
ScreenRatio = 0.9
FrameSizeX = int(ScreenSizeX * ScreenRatio)
FrameSizeY = int(ScreenSizeY * ScreenRatio)
FramePosX = (ScreenSizeX - FrameSizeX)/2
FramePosY = (ScreenSizeY - FrameSizeY)/2
self.geometry("%sx%s+%s+%s"%(FrameSizeX,FrameSizeY,FramePosX,FramePosY))
### Creating 3 "sub-frames" ###
# Frame 1 - canvas container with scrollbar#
self.Canvas1 = Canvas(self, bg = "white")
self.Canvas1.grid(row = 0, column = 0, rowspan = 5, columnspan = 4, sticky = N+E+S+W)
self.Canvas1.rowconfigure(1, weight = 1)
self.Canvas1.columnconfigure(1, weight = 1)
self.myscrollbar=Scrollbar(self, orient = "vertical", command = self.Canvas1.yview)
self.Canvas1.configure(yscrollcommand = self.myscrollbar.set)
self.myscrollbar.grid(row = 0, column = 4, rowspan = 5, sticky = N+S)
# Frame 1 - Frame widget in canvas #
self.Frame1 = Frame(self.Canvas1, bg = "white")
self.Frame1.rowconfigure(0, weight = 1)
for c in range(2):
self.Frame1.columnconfigure(1 + (2 * c), weight = 1)#1,3 - columns for small icons in the future
for cb in range(3):
self.Frame1.columnconfigure((cb * 2), weight = 9)#0,2,4 - columns for data
self.CFrame1 = self.Canvas1.create_window(0, 0, window = self.Frame1, width = FrameSizeX, anchor = N+W)
self.Canvas1.bind("<Configure>", lambda: resize_frame(self)) # !!!!! Doesn't work & gives error !!!!!! #
self.Frame1.bind("<Configure>", lambda: scrollevent(self))
self.Canvas1.config(scrollregion=self.Canvas1.bbox("all"))
# Frame 2 #
self.Frame2 = Frame(self, bg= "yellow")
self.Frame2.grid(row = 5, column = 0, rowspan = 1, columnspan = 3, sticky = W+E+N+S)
for r in range(3):
self.Frame2.rowconfigure(r, weight=1)
for c in range(3):
self.Frame2.columnconfigure(c, weight = 1)
# Frame 3 #
self.Frame3 = Frame(self)
self.Frame3.grid(row = 5, column = 3, rowspan = 1, columnspan = 2, sticky = W+E+N+S)
self.Frame3.rowconfigure(0, weight = 1)
self.Frame3.columnconfigure(0, weight = 1)
# Propagation #
#self.grid_propagate(False) # All widgets (the 3 subframes) need to fit in Toplevel window. Minimal window size will be implemented later.
self.Canvas1.grid_propagate(False) # canvas works with scrollbar, widgets dont need to fit in window size.
#self.Frame1.grid_propagate(False) # Frame1 should resize to hold all data (label-widgets)
self.Frame2.grid_propagate(False) # fixed frame dimensions
self.Frame3.grid_propagate(False) # fixed textbox dimensions
self.Frame1.update_idletasks() # just to make sure
### Widgets for the multiple frames ###
# Frame1 - further populated by button command in frame 2#
self.lblaa = Label(self.Frame1, bg="white", text = "Processing...", justify = "left")
self.lblaa.grid(row = 0, column = 0, sticky = N+W)
self.LSlabelsr = []
self.LSlabelsa = []
self.LSlabelsb = []
# Frame 2 #
self.Wbuttontest=Button(self.Frame2, text="Start listing test", command = lambda: refresh(self))
self.Wbuttontest.grid(row = 0, column = 0, columnspan = 3)
self.Wentry = Entry(self.Frame2)
self.Wentry.grid(row = 2, column = 0, columnspan = 3, sticky = E+W, padx = 10)
self.Wentry.delete(0, END)
self.Wentry.insert(0, "user input here")
# Frame3 #
self.Wtext = Text(self.Frame3)
self.Wscrollb = Scrollbar(self.Frame3)
self.Wscrollb.config(command = self.Wtext.yview)
self.Wtext.config(yscrollcommand = self.Wscrollb.set)
self.Wtext.grid(row = 0, column = 0, sticky = N+E+W+S)
### Test-Lists ### Last character in the left column is "ez" !! ###
self.LSa = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
self.LSb = [1, 2, 3, 4, 66, 6, 7, 8, 9, 67, 11, 12, 13, 14, 68]
self.LSr = []
ib = 0
prefix = ""
for i in range(104):
if ib > 25:
prefix = chr(ord("a") + (i/ib - 1))
ib = 0
else:
pass
self.LSr.append(prefix + chr(97+ib))
ib += 1
### FUNCTIONS ###
def resize_frame(self, event):
self.Canvas1.itemconfig(self.CFrame1, width = e.width) #height of frame should depend on the contents.
def scrollevent(event):
self.Canvas1.configure(scrollregion=self.Canvas1.bbox("all"),width=200,height=200)
def refresh(self): ### Button-command: data will be shown ###
if self.lblaa.winfo_exists() == 1:
self.lblaa.destroy()
for i in range(len(self.LSr)):
self.Frame1.rowconfigure(i, weight = 0)
del self.LSlabelsr[:] # remove any previous labels from if the callback was called before
del self.LSlabelsa[:] # remove any previous labels from if the callback was called before
del self.LSlabelsb[:] # remove any previous labels from if the callback was called before
Vlabelheight = 1
# Left List #
for i in range(len(self.LSr)):
self.LSlabelsr.append(Label(self.Frame1, text = str(self.LSr[i]), bg = "LightBlue", justify = "left", height = Vlabelheight))
self.LSlabelsr[i].grid(row = i, column = 0, sticky = E+W)
# Middle List #
for i in range(len(self.LSa)):
self.LSlabelsa.append(Label(self.Frame1, text = str(self.LSa[i]), bg = "LightBlue", fg = "DarkViolet", justify = "left", height = Vlabelheight))
self.LSlabelsa[i].grid(row = i, column = 2, sticky = E+W)
# Right List #
for i in range(len(self.LSb)):
self.LSlabelsb.append(Label(self.Frame1, text = str(self.LSb[i]), bg = "LightBlue", fg = "DarkGreen", justify = "left", height = Vlabelheight))
self.LSlabelsb[i].grid(row = i, column = 4, sticky = E+W)
self.Frame1.update()
self.Frame1.update_idletasks()
print("done")
if __name__ == "__main__":
root = Tk()
root.title("Invisible")
root.resizable(FALSE,FALSE)
root.withdraw()
app = Processing(root)
root.mainloop()
Working version after suggestions by R4PH4EL:
Proper indentation: the functions were defined as part of the init.
Some tweaks on the lambda commands on line 43/107 & 44/110.
from Tkinter import *
import math
class Processing(Toplevel):
def __init__(self, master, *args, **kwargs):
Toplevel.__init__(self, master)
self.master = master
self.title("Process Window")
for r in range(6):
self.rowconfigure(r, weight = 1)
for c in range(4):
self.columnconfigure(c, weight = 1)
### WINDOW size and position definitions ###
ScreenSizeX = master.winfo_screenwidth()
ScreenSizeY = ( master.winfo_screenheight() - 75 ) #about 75pixels for taskbar on bottom of screen (Windows)
ScreenRatio = 0.9
FrameSizeX = int(ScreenSizeX * ScreenRatio)
FrameSizeY = int(ScreenSizeY * ScreenRatio)
FramePosX = (ScreenSizeX - FrameSizeX)/2
FramePosY = (ScreenSizeY - FrameSizeY)/2
self.geometry("%sx%s+%s+%s"%(FrameSizeX,FrameSizeY,FramePosX,FramePosY))
### Creating 3 "sub-frames" ###
# Frame 1 - canvas container with scrollbar#
self.Canvas1 = Canvas(self, bg = "white")
self.Canvas1.grid(row = 0, column = 0, rowspan = 5, columnspan = 4, sticky = N+E+S+W)
self.Canvas1.rowconfigure(1, weight = 1)
self.Canvas1.columnconfigure(1, weight = 1)
self.myscrollbar=Scrollbar(self, orient = "vertical", command = self.Canvas1.yview)
self.Canvas1.configure(yscrollcommand = self.myscrollbar.set)
self.myscrollbar.grid(row = 0, column = 4, rowspan = 5, sticky = N+S)
# Frame 1 - Frame widget in canvas #
self.Frame1 = Frame(self.Canvas1, bg = "white")
self.Frame1.rowconfigure(0, weight = 1)
for c in range(2):
self.Frame1.columnconfigure(1 + (2 * c), weight = 1)#1,3 - columns for small icons in the future
for cb in range(3):
self.Frame1.columnconfigure((cb * 2), weight = 9)#0,2,4 - columns for data
self.CFrame1 = self.Canvas1.create_window(0, 0, window = self.Frame1, width = FrameSizeX, anchor = N+W)
self.Canvas1.bind("<Configure>", lambda event: self.resize_frame(event)) # !!!!! Doesn't work & gives error !!!!!! #
self.Frame1.bind("<Configure>", lambda event: self.scrollevent(event))
self.Canvas1.config(scrollregion=self.Canvas1.bbox("all"))
# Frame 2 #
self.Frame2 = Frame(self, bg= "yellow")
self.Frame2.grid(row = 5, column = 0, rowspan = 1, columnspan = 3, sticky = W+E+N+S)
for r in range(3):
self.Frame2.rowconfigure(r, weight=1)
for c in range(3):
self.Frame2.columnconfigure(c, weight = 1)
# Frame 3 #
self.Frame3 = Frame(self)
self.Frame3.grid(row = 5, column = 3, rowspan = 1, columnspan = 2, sticky = W+E+N+S)
self.Frame3.rowconfigure(0, weight = 1)
self.Frame3.columnconfigure(0, weight = 1)
# Propagation #
#self.grid_propagate(False) # All widgets (the 3 subframes) need to fit in Toplevel window. Minimal window size will be implemented later.
self.Canvas1.grid_propagate(False) # canvas works with scrollbar, widgets dont need to fit in window size.
#self.Frame1.grid_propagate(False) # Frame1 should resize to hold all data (label-widgets)
self.Frame2.grid_propagate(False) # fixed frame dimensions
self.Frame3.grid_propagate(False) # fixed textbox dimensions
self.Frame1.update_idletasks() # just to make sure
### Widgets for the multiple frames ###
# Frame1 - further populated by button command in frame 2#
self.lblaa = Label(self.Frame1, bg="white", text = "Processing...", justify = "left")
self.lblaa.grid(row = 0, column = 0, sticky = N+W)
self.LSlabelsr = []
self.LSlabelsa = []
self.LSlabelsb = []
# Frame 2 #
self.Wbuttontest=Button(self.Frame2, text="Start listing test", command = lambda: self.refresh())
self.Wbuttontest.grid(row = 0, column = 0, columnspan = 3)
self.Wentry = Entry(self.Frame2)
self.Wentry.grid(row = 2, column = 0, columnspan = 3, sticky = E+W, padx = 10)
self.Wentry.delete(0, END)
self.Wentry.insert(0, "user input here")
# Frame3 #
self.Wtext = Text(self.Frame3)
self.Wscrollb = Scrollbar(self.Frame3)
self.Wscrollb.config(command = self.Wtext.yview)
self.Wtext.config(yscrollcommand = self.Wscrollb.set)
self.Wtext.grid(row = 0, column = 0, sticky = N+E+W+S)
### Test-Lists ### Last character in the left column is "ez" !! ###
self.LSa = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
self.LSb = [1, 2, 3, 4, 66, 6, 7, 8, 9, 67, 11, 12, 13, 14, 68]
self.LSr = []
ib = 0
prefix = ""
for i in range(104):
if ib > 25:
prefix = chr(ord("a") + (i/ib - 1))
ib = 0
else:
pass
self.LSr.append(prefix + chr(97+ib))
ib += 1
### FUNCTIONS ###
def resize_frame(self, e):
self.Canvas1.itemconfig(self.CFrame1, width = e.width) #height of frame should depend on the contents.
def scrollevent(self, event):
self.Canvas1.configure(scrollregion=self.Canvas1.bbox("all"),width=200,height=200)
def refresh(self): ### Button-command: data will be shown ###
if self.lblaa.winfo_exists() == 1:
self.lblaa.destroy()
for i in range(len(self.LSr)):
self.Frame1.rowconfigure(i, weight = 0)
del self.LSlabelsr[:] # remove any previous labels from if the callback was called before
del self.LSlabelsa[:] # remove any previous labels from if the callback was called before
del self.LSlabelsb[:] # remove any previous labels from if the callback was called before
Vlabelheight = 1
# Left List #
for i in range(len(self.LSr)):
self.LSlabelsr.append(Label(self.Frame1, text = str(self.LSr[i]), bg = "LightBlue", justify = "left", height = Vlabelheight))
self.LSlabelsr[i].grid(row = i, column = 0, sticky = E+W)
# Middle List #
for i in range(len(self.LSa)):
self.LSlabelsa.append(Label(self.Frame1, text = str(self.LSa[i]), bg = "LightBlue", fg = "DarkViolet", justify = "left", height = Vlabelheight))
self.LSlabelsa[i].grid(row = i, column = 2, sticky = E+W)
# Right List #
for i in range(len(self.LSb)):
self.LSlabelsb.append(Label(self.Frame1, text = str(self.LSb[i]), bg = "LightBlue", fg = "DarkGreen", justify = "left", height = Vlabelheight))
self.LSlabelsb[i].grid(row = i, column = 4, sticky = E+W)
self.Frame1.update()
self.Frame1.update_idletasks()
print("done")
if __name__ == "__main__":
root = Tk()
root.title("Invisible")
root.resizable(FALSE,FALSE)
root.withdraw()
app = Processing(root)
root.mainloop()
Either your indentation is wrong or your getting something wrong in general.
All of your functions are defined inside your __init__ function
Second: if you want to call a class function, you call it by obj.function
Your error on lambda: resize(self) may occur as it should be lambda: self.resize.
Give it a shot with this one and try it.
And please make sure your indentations are correct.
I totally agree with Bryan here - ommiting the lambdas it would be (my personal opinion) easier to read and kind of "better" in a meaning of more structured and pragmatic coding style.
I'm starting to code with Python and on my first application I have reached a brick wall. Any help on why this code is not displaying the widgets will be greatly appreciated!
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def _init_(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.header_frame, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 0, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp()
root.mainloop()
if __name__ == '__main__':
main()
Everytime I launch the code I get a blank tkinter window.
This had a few problems.
You had an _init_ method, not an __init__ method, so the created object wasn't being initialized.
You have to send the root tkinter object to the application, with app = ImprintPlusApp(root).
You had a self.header_frame once instead of self.frame_header.
You had a columnspan = 0 (which is invalid) instead of columnspan = 1 (which doesn't really need to be specified).
I've made the above changes in the code below. It may still need debugging, as I don't know exactly what design you had in mind.
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class ImprintPlusApp:
def __init__(self, master):
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.frame_header, text = "Bienvenidos a Imprint Plus Manager")
self.frame_crearorden = ttk.Frame(master)
self.frame_crearorden.pack()
ttk.Label(self.frame_crearorden, text = "Nombre").grid(row = 0, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Email").grid(row = 2, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Numero Cel/Tel").grid(row = 4, column = 0, padx = 5)
ttk.Label(self.frame_crearorden, text = "Información Adicional").grid(row = 6, column = 0, padx = 5)
self.entry_name = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_email = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_numtc = ttk.Entry(self.frame_crearorden, width = 24)
self.entry_addinf = Text(self.frame_crearorden, width = 50, height = 10)
self.entry_name.grid(row = 0, column = 1, padx = 5)
self.entry_email.grid(row = 2, column = 1, padx = 5)
self.entry_numtc.grid(row = 4, column = 1, padx = 5)
self.entry_addinf.grid(row = 7, column = 0, columnspan = 2, padx = 5)
ttk.Button(self.frame_crearorden, text = "Submit", command = self.submit).grid(row = 8, columnspan = 1, padx = 5)
ttk.Button(self.frame_crearorden, text = "Clear", command = self.clear).grid(row = 8, columnspan = 1, padx = 5)
def submit(self):
print ("Nombre: {}".format(self.entry_name.get()))
print ("Email: {}".format(self.entry_name.get()))
print ("Num Cel/Tel: {}".format(self.entry_name.get()))
print ("Información Adicional: {}".format(self.entry_name.get(1.0, "end")))
self.clear()
messagebox.showinfo(tite = "Orden #", message = "Orden Guardada")
def clear(self):
self.entry_name.delete(0, "end")
self.entry_email.delete(0, "end")
self.entry_numtc.delete(0, "end")
self.entry_addinf.delete(1.0, "end")
def main():
root = Tk()
app = ImprintPlusApp(root)
root.mainloop()
if __name__ == '__main__':
main()
Well, I've looked a lot in the web before asking, so here's the thing.
I'm not really experienced in Python and I need to develop this Matrix Generator. Yes, it is a mathematics matrix. I'm using Tkinter and Python 3.3.
First i ask the Number of Rows and Columns and then I fill each field and the code transforms it in a notepad for other programs to read.
I used the grid method so i'm having trouble with large scale matrices. The thing is I need to apply a scrollbar. I have read that I can use frame and a friend of mine showed me a scrollbar he made using frames. Can you help me? ;D
Every time I refer to linhas is the same as rows and colunas is the same as columns.
import tkinter
class DropDown:
def __init__(self):
self._list_window = tkinter.Tk();
self._row_var = tkinter.StringVar(self._list_window)
self._col_var = tkinter.StringVar(self._list_window)
self._row_var.set(0)
self._col_var.set(0)
self._rows = None
self._columns = None
self._row_label = tkinter.Label(
master = self._list_window,
text = 'Number of rows: ')
self._row_label.grid(
row = 0, column = 0, padx = 5, pady = 5,
sticky = tkinter.NE)
self._row_entry = tkinter.Entry(self._list_window, width=1)
self._row_entry.grid(
row = 0, column = 1, padx = 5, pady = 5,
sticky = tkinter.EW)
self._column_label = tkinter.Label(
master = self._list_window,
text = 'Number of columns: ')
self._column_label.grid(
row = 1, column = 0, padx = 5, pady = 5,
sticky = tkinter.NE)
self._column_entry = tkinter.Entry(self._list_window)
self._column_entry.grid(
row = 1, column = 1, padx = 5, pady = 5,
sticky = tkinter.EW)
self._list_window.columnconfigure(1, weight = 1)
self._OK_button = tkinter.Button(
master = self._list_window, text = "OK",
command = self.get_dimensions)
self._OK_button.grid(
row = 2, column = 0, columnspan = 2,
padx = 5, pady = 5)
def get_dimensions(self):
self._rows = self._row_entry.get()
self._columns = self._column_entry.get()
self._list_window.destroy()
def show(self):
self._list_window.mainloop()
if self._rows != None and self._columns != None:
return (int(self._rows), int(self._columns))
else:
return (None, None)
class matrix:
def __init__(self, linhas, colunas):
self.linhas=linhas
self.colunas=colunas
self.mwindow=tkinter.Tk()
self.vars = [[] for x in range(self.linhas) ]
for i in range(self.linhas):
for j in range(self.colunas):
v=tkinter.StringVar()
self.vars[i].append(v)
entry = tkinter.Entry(master = self.mwindow, textvariable = self.vars[i][j])
entry.grid(row = i, column = j, padx = 10, pady = 10)
self.botOK=tkinter.Button(master=self.mwindow, text="OK", command=self.OK)
self.botOK.grid(row=self.linhas+1, column=(self.colunas//2)-1, columnspan=2, padx=5, pady=5)
def Start(self):
self.mwindow.mainloop()
return self.lista
def OK(self):
self.lista = []
for i in range(self.linhas):
for j in range(self.colunas):
self.lista.append(self.vars[i][j].get())
self.mwindow.destroy()
dimensoes= DropDown().show()
#print (dimensoes)
if dimensoes[0]<dimensoes[1]:
diag=dimensoes[0]
else:
diag=dimensoes[1]
matriz=matrix(dimensoes[0], dimensoes[1]).Start()
with (open("notepadmatrix.txt", "w")) as arquivo:
arquivo.write(str(dimensoes[0]*dimensoes[1])+"\n")
arquivo.write(str(dimensoes[0])+"\n")
arquivo.write(str(dimensoes[1])+"\n")
arquivo.write(str(diag)+"\n")
for i in matriz:
arquivo.write(i+"\n")
arquivo.write("fim")
and here goes the code he gave me to the scroll bar.
class Earnings():
def __init__(self, Ticker, EPS, Time):
self._root_window = tkinter.Tk()
self.canvas = tkinter.Canvas(master = self._root_window, background = '#8989E0')
self.canvas.config(scrollregion=[0,0,600,10000])
self.frame = tkinter.Frame(master = self.canvas)
self.scrollbar = tkinter.Scrollbar(master = self._root_window, orient = tkinter.VERTICAL)
self.frame.pack(side = tkinter.LEFT, fill = tkinter.BOTH, expand = tkinter.TRUE)
self.canvas.create_window((0,0), window=self.frame, anchor=tkinter.NW)
self.scrollbar.pack(side = tkinter.RIGHT, fill = tkinter.BOTH, expand = tkinter.TRUE)
self.canvas.pack(side = tkinter.TOP, fill = tkinter.BOTH, expand = tkinter.TRUE)
self.scrollbar.config(command = self.canvas.yview)
self.canvas.config(yscrollcommand = self.scrollbar.set)
self.ticker = Ticker
self.EPS = EPS
self.time = Time
for i in range(len(self.ticker)):
self.TickerButton = tkinter.Button(
master = self.frame,
text = self.ticker[i],
command = lambda i=i: self.search_ticker(self.ticker[i]))
self.TickerButton.grid(row = i+1, column = 0, padx = 10, pady = 10,
sticky = tkinter.W)
self.EPSLabel = tkinter.Label(
master = self.frame,
text = self.EPS[i])
self.EPSLabel.grid(row = i+1, column = 1, padx = 10, pady = 10,
sticky = tkinter.W)
self.TimeLabel = tkinter.Label(
master = self.frame,
text = self.time[i])
self.TimeLabel.grid(row = i+1, column = 2, padx = 10, pady = 10,
sticky = tkinter.W)
TkInter is long in the tooth, I'd use Kivy Grid layout instead:
http://kivy.org/docs/api-kivy.uix.gridlayout.html?highlight=grid
Basically i've wrote a GUI, to make a maths game and have linked it to my microsft access database using sql, however i cannot get my questions to print to my label, any ideas ?. Also how do you generate a random number from my list of questions, as you can see my jim statement doesnt work.
import Tkinter
import Databaseconnector
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
jim = randomnumber()
SQL = 'SELECT * FROM tblQuestion'
cursor = Databaseconnector.SELECT(SQL)
rows = cursor.fectchall()
for row in rows:
print row.Question, row.Hint, row.A1, row.A2, row.A3, row.A4, row.CorrectAnswer
alabel2.set("Question: " + (row.question)(jim).Item(1))
def create_widgets(self):
# create welcome label
label1 = Tkinter.Label(self, text = "Question Game !")
label1.grid(row = 0, column = 1, columnspan = 2, sticky = 'W')
# create intruction label
alabel2 = Tkinter.Label(self, text = "")
alabel2.grid(row = 1, column = 0, columnspan = 2, sticky = 'W')
a1loginbutton = Tkinter.Button(self, text = "Enter",)
a1loginbutton.grid(row = 9, column = 1, sticky = 'W')
label3 = Tkinter.Label(self, text = "")
label3.grid(row = 10, column = 0, columnspan = 2, sticky = 'W')
a2loginbutton = Tkinter.Button(self, text = "Enter",)
a2loginbutton.grid(row = 11, column = 1, sticky = 'W')
a3loginbutton = Tkinter.Button(self, text = "Enter",)
a3loginbutton.grid(row = 9, column = 3, sticky = 'E')
a4loginbutton = Tkinter.Button(self, text = "Enter",)
a4loginbutton.grid(row = 11, column = 3, sticky = 'E')
label4 = Tkinter.Label(self, text = "")
label4.grid(row = 12, column = 0, columnspan = 2, sticky = 'W')
hiloginbutton = Tkinter.Button(self, text = "Hint",)
hiloginbutton.grid(row = 13, column = 3, sticky = 'E')
label5 = Tkinter.Label(self, text = "Score:")
label5.grid(row = 14, column = 1, columnspan = 5, sticky = 's')
def close_page(self):
self.destroy()
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('my application')
app.geometry("150x200")
app.mainloop()
Edited based on comments from OP:
There is a typo in this line: rows = cursor.fectchall()
Try changing the label.set statement to a simple case to confirm that this works. alabel2.set("Question: " + row.question)
What is the randomnumber() function, and what is the (row.question)(jim).Item(1) line supposed to return?