The problem in that I can't pickle the text in entry fields. I try to make it in the 'record' function.
Error: can't pickle _tkinter.tkapp objects
I want to save data in the file and then read it.
Interface:
#program to record and store your sports results
import shelve
from tkinter import *
class Application(Frame):
'''GUI application ере displays menu for the programm'''
def __init__(self, master):
'''Initialize Frame'''
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
''' Create widgets to get story information and to display story. '''
self.fileDat = 'data'
# label date
Label(self,
text = "date:"
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
# field date
self.date_ent = Entry(self)
self.date_ent.grid(row = 1, column = 1, sticky = W)
# label №
Label(self,
text = "№:"
).grid(row = 0, column = 3, columnspan = 2, sticky = W)
# field №
self.number_ent = Entry(self)
self.number_ent.grid(row = 1, column = 4, sticky = W)
# label km
Label(self,
text = "km:"
).grid(row = 2, column = 0, columnspan = 2, sticky = W)
# field km
self.km_ent = Entry(self)
self.km_ent.grid(row = 3, column = 1, sticky = W)
# label time
Label(self,
text = "time:"
).grid(row = 3, column = 0, columnspan = 2, sticky = W)
# field time
self.time_ent = Entry(self)
self.time_ent.grid(row = 4, column = 1, sticky = W)
# record button
Button(self,
text = "record training",
command = self.record
).grid(row = 5, column = 0, sticky = W)
# show training button
Button(self,
text = "show trining",
command = self.tngDisplay
).grid(row = 5, column = 3, sticky = W)
self.tngField = Text(self, width = 75, height = 10, wrap = WORD)
self.tngField.grid(row = 6, column = 0, columnspan = 4)
def listRecord( self):
date = self.date_ent.get()
km = self.km_ent.get()
time = self.time_ent.get()
tng = [date,km, time]
return tng
def record (self):
tngList = self.listRecord
tngNumber = self.number_ent.get()
datFile = shelve.open(self.fileDat)
datFile[tngNumber] = tngList
#datFile['1'] = tngList
datFile.sync()
datFile.close()
def tngDisplay (self):
tng = ''
self.tngField.delete(0.0, END)
#i=0
datFile = shelve.open(self.fileDat)
for key, item in datFile.items():
tng = str(key) + ': ' + str(item)
# display trainings
self.tngField.insert(0.0, tng)
#i+=1
root = Tk()
root.title('RunForest')
app = Application(root)
root.mainloop()
Related
I have a little problem with the checkbtn value.
Here is my code:
def select_data():
select_window = Tk()
var_autotrader = IntVar()
check_sites_autotrader = Checkbutton(select_window, text = 'autotrader', variable = var_autotrader)
var_bestcarfinder = IntVar()
var_cardady = IntVar()
var_cars = IntVar()
var_car_gurus = IntVar()
var_iseecars = IntVar()
var_truecar = IntVar()
check_sites_bestcarfinder = Checkbutton(select_window, text = 'bestcarfinder', variable = var_bestcarfinder)
check_sites_cardaddy = Checkbutton(select_window, text = 'cardady', variable = var_cardady)
check_sites_cars = Checkbutton(select_window, text = 'cars.com', variable = var_cars)
check_sites_car_gurus = Checkbutton(select_window, text = 'car gurus', variable = var_car_gurus)
check_sites_iseecars = Checkbutton(select_window, text = 'iseecars', variable = var_iseecars)
check_sites_truecar = Checkbutton(select_window, text = 'truecar', variable = var_truecar)
check_sites_autotrader.grid(row = 0, column = 0, sticky = W)
check_sites_bestcarfinder.grid(row = 1, column = 0, sticky = W)
check_sites_cardaddy.grid(row = 2, column = 0, sticky = W)
check_sites_cars.grid(row = 3, column = 0, sticky = W)
check_sites_car_gurus.grid(row = 4, column = 0, sticky = W)
check_sites_iseecars.grid(row = 5, column = 0, sticky = W)
check_sites_truecar.grid(row = 6, column = 0, sticky = W)
def upload_selected_data():
print(var_autotrader.get())// This one does not give me 1 when check is on
btn = Button(select_window, text = 'go!', command = upload_selected_data)
btn.grid(row = 7, column = 0, sticky = W+E)
The trouble is that my variable is not changing when I check the box
Thank you very much!
Probably you created your "main window" with Tk(). In this case you should create another window with the Toplevel() (Not with Tk()).
It means in your case you should change the select_window = Tk() line to select_window = Toplevel()
this my situation. I'm learning how to use python (I just started) to create a GUI with Tkinter. One requirement of my application is to be able to store "DateEntry", while investigating I came across with tkcalendar DateEntry. The problem is that DateEntry is created as a class but my already created window(GUI) is a class as well and I don't know how to combine the class DateEntry into my class client which creates a mainwindow, I think that's beyond my knowledge. I want a DateEntry to be displayed in another toplevel() window when the button "Fecha Check-in" is used. Can anyone explain how to do it?
this is the image
This is the code:
from tkcalendar import DateEntry
from datetime import date
from tkinter import ttk
from tkinter import *
import sqlite3
#year = datetime.date.today().year
#month = datetime.date.today().month
class client:
def __init__(self, window):
self.wind = window
self.wind.title('Start Bits CheckIn-CheckOut')
#self.wind.columnconfigure(0, weight = 1)
#self.wind.rowconfigure(0, weight = 1)
#self.wind.geometry("330x300")
frame_2 = Label(self.wind, text = 'Registro de huéspedes')
frame_2.grid(row = 0, column = 0, pady = 5)
#
frame = LabelFrame(self.wind, text = 'Datos personales', borderwidth=4, relief="raised")
frame.grid(row = 1, column = 0, columnspan = 10, pady = 2, sticky = W + E)
#
# #label ID
L_ID = Label(frame, text = 'Cédula: ').grid(row = 1, column = 0, padx = 1, pady = 1)
self.ID = Entry(frame, width = 25)
self.ID.focus()
self.ID.grid(row = 1, column = 1, columnspan = 2)
#label Nombre
L_name = Label(frame, text = 'Nombres: ').grid(row = 2, column =0, padx = 1, pady = 2)
self.nombre = Entry(frame, width = 25)
self.nombre.grid(row = 2, column = 1, columnspan = 2)
#label last
L_last = Label(frame, text = 'Apellidos: ').grid(row = 3, column = 0, padx = 1, pady = 2)
self.last = Entry(frame, width = 25)
self.last.grid(row = 3, column = 1, columnspan = 2)
#label contact phone
L_phone = Label(frame, text = 'Teléfono: ').grid(row = 4, column = 0, padx = 1, pady = 2)
self.phone = Entry(frame, width = 25)
self.phone.grid(row = 4, column = 1, columnspan = 2)
#label email
L_mail = Label(frame, text = 'Email: ').grid(row = 5, column = 0, padx = 1, pady = 2)
self.mail = Entry(frame, width = 25)
self.mail.grid(row = 5, column = 1, columnspan = 2)
#label CheckIn
L_ChkIN = Label(frame, text = 'Check-In: ').grid(row = 6, column = 0, padx = 1, pady = 5)
ttk.Button(frame, text = 'Fecha Check-In', command = self.fecha_In).grid(row = 6, column = 2)
#label CheckOut
L_ChkOut = Label(frame, text = 'Check-Out').grid(row = 7, column = 0, padx = 1, pady = 5)
#button registrar
ttk.Button(frame, text = 'Registrar' ).grid(row = 2, column = 6, padx = 10)
#button actualizar
ttk.Button(frame, text = 'Actualizar').grid(row = 4, column = 6, padx = 10)
def fecha_In(self):
self.fecha_in = Toplevel()
self.fecha_in.title = 'Fecha Check-In'
if __name__ == '__main__':
window = Tk()
style = ttk.Style(window)
style.theme_use('clam')
alien = PhotoImage(file = "Start Bits.png")
fondo = Label(window, image = alien).grid(row = 8, column = 0)
application = client(window)
window.mainloop()
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?