I am attempting to create a python script to calculate the shortest trip around a set of colleges. i need to add a starting point, but ive confused myself beyond belief to the point of no return. Can anyone help me figure out where to go from here
from Tkinter import *
import tkMessageBox, tkFileDialog
import json
import re
from urllib import urlopen
import math
class Application(Frame):
collegelist = []
collegelist1 = []
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.top_frame = Frame(self)
self.mid_frame = Frame(self)
self.bot_frame = Frame(self, bg = 'red')
self.top_frame.pack(side = 'top')
self.mid_frame.pack(side = 'top')
self.bot_frame.pack(side = 'top')
#top frame
self.label1 = Label(self.top_frame, text = "Your College Choices", bg ='red')
self.label1.pack(side = 'left', padx='40', pady='0')
self.label2 = Label(self.top_frame, text = "Your Tour Selections", bg ='green')
self.label2.pack(side = 'right', padx='40')
#mid frame
self.mylist = Listbox(self.mid_frame,
bg = 'black',
fg = 'gold')
self.mylist.pack(side='left')
self.my_button1 = Button(self.mid_frame, text = '>>>', command=self.getlist)
self.my_button2 = Button(self.mid_frame, text = '<<<', command=self.returnlist)
self.my_button1.pack(side="left")
self.my_button2.pack(side="left")
self.mylist1 = Listbox(self.mid_frame,
selectmode=DISABLED,
bg = 'black',
fg = 'gold')
self.mylist1.pack(side='right')
#bottom frame
self.openbutton = Button(self.bot_frame, text='Open File', command=self.openfile, fg ='green')
self.openbutton.pack(side='left')
self.my_button = Button(self.bot_frame, text = 'Route', fg ='green', command=self.collegeroute)
self.my_button.pack(side='left')
self.quit_button = Button(self.bot_frame, text = 'Quit',
command = self.quit, fg = 'green')
self.quit_button.pack(side='left')
def openfile(self):
filename = tkFileDialog.askopenfilename(title='Choose a file')
if filename:
clist = open(filename, "r")
for line in clist.readlines():
for i in line.split():
self.collegelist.append(i)
for college in self.collegelist:
self.mylist.insert(1,college)
def getlist(self):
# get selected line index
index = [int(x) for x in self.mylist.curselection()]
print index
for i in index:
seltext = self.mylist.get(i)
self.mylist.delete(i)
self.mylist1.insert(1,seltext)
self.collegelist1.append(seltext)
print seltext
def returnlist(self):
# get selected line index
index = [int(x) for x in self.mylist1.curselection()]
for i in index:
seltext = self.mylist1.get(i)
self.mylist1.delete(i)
seltext = seltext.strip()
seltext = seltext.replace(' ', '')
self.mylist.insert(0,seltext)
self.collegelist1.remove(seltext)
def collegeroute(self):
# get selected line index
global tuplist
self.tuplist =[]
for college in self.collegelist1:
f = urlopen('http://graph.facebook.com/%s' % college) #load in the events
d = json.load(f)
longitude = d["location"]["longitude"]
latitude = d["location"]["latitude"]
name = d['name']
self.tuplist.append((latitude, longitude))
cartesian_matrix(self.tuplist)
def cartesian_matrix(coords):
'''create a distance matrix for the city coords
that uses straight line distance'''
matrix={}
for i,(x1,y1) in enumerate(coords):
for j,(x2,y2) in enumerate(coords):
dx,dy=x1-x2,y1-y2
dist=math.sqrt(dx*dx + dy*dy)
matrix[i,j]=dist
tour_length(matrix,collegelist1)
return matrix
def tour_length(matrix,tour):
total=0
num_cities=len(tour)
print tour
print num_cities
for i in range(num_cities):
j=(i+1)%num_cities
city_i=tour[i]
city_j=tour[j]
total+=matrix[city_i,city_j]
print total
def getRad(x):
return float(x) * (math.pi/180.0)
def main():
app = Application()
app.master.title("My Application")
app.mainloop()
if __name__ == "__main__":
main()
Having trouble getting the tour_length to work
You are calling tour_length and returning from cartesian_matrix in the wrong place. You are only doing one row of the matrix, then calling tour_length and returning.
Having trouble getting the tour_length to work
The only obvious problem with tour_length that I see is that you're failing to return the result. Add the following at the end:
return total
Upon closer inspection, the following also looks suspect:
tour_length(matrix,collegelist1)
return matrix
Firstly, it's mis-indented. Secondly, you're ignoring the return value of tour_length.
The mis-indentation is probably what's causing the exception (you're calling tour_length before you have fully initialized matrix).
Related
I am writing an application for a digital lab balance that connects over serial. To build the application I set up a COM port bridge and wrote a program to simulate the balance on my machine (the balance was in use). I will show you the most recent version of the balance simulation program:
import serial, random, time
s = serial.Serial('COM2')
#Initially we will just push a random float
#After the data the scale sends a carraige return + line feed
def pushData():
data = f'{round(random.uniform(10, 100), 2)}\r\n'.encode()
print(f'Sending Data: {data}')
s.write(data)
try:
while True:
pushData()
time.sleep(10)
except:
print('Something went wrong.')
This code along with my balance application works as expected on my machine. But when I try to use my balance program with the actual device it does not get all the serial data if it even works at all. I am wondering if I need some kind of multi-threading, if its a timing issue or something. I know the balance works because I can monitor the COM port.
I will post my most recent balance program here:
# !/usr/bin/python3
################ Imports
import serial, pyperclip
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import datetime, time
from tkinter import *
################ Declarations
GUI = Tk()
s = serial.Serial('COM5', timeout=1)
wgtList = [0,0,0,0,0]
wgtDict = {'Lab':[],
'Weight':[]}
newL = '\r\n'
tareWgt = 0
newWgt = 0 #Trying to get past program not working when no data is pushed
################ Functions
def thisAfter():
"""Updates scale feed and updates the scale feed."""
try:
global newWgt
newWgt = float(s.readline().decode().rstrip('\r\n')) - tareWgt
except ValueError:
#print('ValueError thisAfter(): NO DATA OR COULD NOT CONVERT SERIAL DATA TO FLOAT')
print('ValueError thisAfter(): '+ str(newWgt))
print('wgtList: '+ str(wgtList))
wgtList.append(newWgt)
if newWgt not in wgtList[0:5]:
text.insert(INSERT,str(newWgt)+newL)
if len(wgtList) > 5:
del wgtList[0]
GUI.after(50, thisAfter)
text.see(END)
def labCallback():
"""Saves data to file, iterates the entry field."""
num = labEntry.get()
csvStr = datetime.today().strftime("%Y/%m/%d") + ',' + datetime.now().strftime("%H:%M:%S") + ',' + num + ',' + str(wgtList[-1]) + ',' + var1.get() + ',' + str(tareWgt) + newL
with open('data.csv', 'a+', newline = '') as file:
if file.readline() == None:
file.write('Date, Time, Lab, Weight, Type' + newL)
file.write(csvStr)
#print(csvStr) #Just checking
labEntry.delete(0,END)
labEntry.insert(0, int(num) + 1)
csvArr = csvStr.split(',')
wgtDict['Lab'].append(int(csvArr[2]))
wgtDict['Weight'].append(float(csvArr[3]))
text2.insert(INSERT, ',\t'.join(csvArr))
text2.see(END)
#print(str(wgtDict)+'\n')
def tareCallback():
global tareWgt
tareWgt = wgtList[-1]
print(tareWgt)
text3.insert(INSERT,newL+str(tareWgt))
text3.see(END)
def copyData():
global newWgt
pyperclip.copy(newWgt)
def close():
s.close()
def start():
global s
try:
s = serial.Serial('COM5', timeout=1)
thisAfter()
except:
print('Serial port closed')
################ Frames/Panes
frame1 = LabelFrame(GUI, text = 'Lab Label + Entry Field')
frame1.pack(side = TOP)
frame6 = LabelFrame(frame1, text = 'Tare')
frame6.pack(side = BOTTOM)
frame2 = LabelFrame(GUI, text = 'Scale Feed')
frame2.pack(side = BOTTOM)
frame3 = LabelFrame(GUI, text = 'Saved Feed')
frame3.pack(side = BOTTOM)
frame4 = LabelFrame(GUI, text = 'Plot')
frame4.pack(side = TOP)
frame5 = LabelFrame(frame1, text = 'Type Select')
frame5.pack(side = BOTTOM)
################ Lab Label + Entry Field + Type Select
labLabel = Label(frame1, bd = 5, text = 'Lab#')
labLabel.pack(side = LEFT)
tareLabel = Label(frame6, bd = 5, text = 'Tare')
tareLabel.pack(side = LEFT)
text3 = Text(frame6, height = 1, width = 20)
text3.pack(side = RIGHT)
closeButton = Button(frame1, text = 'Close', command = close)
closeButton.pack(side = RIGHT)
startButton = Button(frame1, text = 'Start', command = start)
startButton.pack(side = RIGHT)
tareButton = Button(frame1, text = 'Tare', command = tareCallback)
tareButton.pack(side = RIGHT)
undoButton = Button(frame1, text = 'Undo')
undoButton.pack(side = RIGHT)
labButton = Button(frame1, text = 'Save', command = labCallback)
labButton.pack(side = RIGHT)
copyButton = Button(frame1, text = 'Copy', command = copyData)
copyButton.pack(side = RIGHT)
labEntry = Entry(frame1)
labEntry.pack(side = RIGHT)
var1 = StringVar()
r1 = Radiobutton(frame5, text = 'pH', variable= var1, value = 'pH')
r1.pack(anchor = 's')
r2 = Radiobutton(frame5, text = 'pH-Tray', variable= var1, value = 'pH-Tray')
r2.pack(anchor = 's')
r3 = Radiobutton(frame5, text = 'Mehlich', variable= var1, value = 'Mehlich')
r3.pack(anchor = 's')
r4 = Radiobutton(frame5, text = 'Nitrate', variable= var1, value = 'Nitrate')
r4.pack(anchor = 's')
r5 = Radiobutton(frame5, text = 'Excel', variable= var1, value = 'Excel')
r5.pack(anchor = 's')
r6 = Radiobutton(frame5, text = 'Excel-Tray', variable= var1, value = 'Excel-Tray', state=DISABLED)
r6.pack(anchor = 's')
r1.select()
r2.deselect()
r3.deselect()
r4.deselect()
r5.deselect()
r6.deselect()
################ Scale Feed
scrollbar = Scrollbar(frame2)
scrollbar.pack(side = RIGHT, fill = Y)
text = Text(frame2, yscrollcommand = scrollbar.set, height = 10)
text.pack()
text.bind('<ButtonPress>', lambda e: 'break')
scrollbar.config(command = text.yview)
#thisAfter()
################ Saved Feed
scrollbar = Scrollbar(frame3)
scrollbar.pack(side = RIGHT, fill = Y)
text2 = Text(frame3, yscrollcommand = scrollbar.set, height = 10)
text2.pack()
scrollbar.config(command = text.yview)
################ Plot
f = plt.Figure(dpi=50, figsize=(13, 4))
plt.xkcd()
a = f.add_subplot(111)
def animate(i):
xL = wgtDict['Lab']
yL = wgtDict['Weight']
a.clear()
a.plot(xL, yL)
canvas = FigureCanvasTkAgg(f, frame4)
canvas.get_tk_widget().pack(side = LEFT, fill = BOTH)
ani = animation.FuncAnimation(f, animate, interval=1000)
# This is some kind of 'while true' loop fyi
GUI.mainloop()
import Tkinter
import random
class die:
def __init__(self,dieNum,frame,game):
self.button = Tkinter.Button(frame,
text = ' ',
command = self.rollDie,
font = ('Garamond', 30),
bg = 'white')
self.button.pack(side = 'left')
self.game = game
self.value = ' '
self.num = dieNum
def rollDie(self):
if self.value == ' ':
self.button.config(text = self.game.Player)
self.value = self.game.Player
self.game(self.num)
class DiceRoller:
def __init__(self):
self.gameWin = Tkinter.Tk()
self.gameFrame = Tkinter.Frame(self.gameWin)
self.dice = [ ]
self.Row1 = Tkinter.Frame(self.gameWin)
for i in range(1):
self.dice.append(die(i,self.Row1,self))
self.Row2 = Tkinter.Frame(self.gameWin)
for i in range(2):
self.dice.append(die(i,self.Row2,self))
self.Row3 = Tkinter.Frame(self.gameWin)
for i in range(3):
self.dice.append(die(i,self.Row3,self))
self.topFrame = Tkinter.Frame(self.gameWin)
self.rollBtn = Tkinter.Button(self.topFrame,
text = 'Roll Again',
command = self.randomNumber,
font = ('Garamond', 30))
self.rollBtn.pack(side = 'left')
def randomNumber(self):
self.value = random.randint(1,6)
self.display.config(text = str(self.value))
self.Row1.pack()
self.Row2.pack()
self.Row3.pack()
self.gameFrame.pack()
self.topFrame.pack()
self.gameWin.mainloop()
DR = DiceRoller()
DR
This is my first time using Tkinter and my first time working with classes, so I feel a bit in over my head.
Basically, when I run the code I get a loading wheel by my pointer, but nothing opens.
I am trying to alter a similar code to create a dice roller, but I cannot tell where the error is just by comparing the two.
hi I'm a student and I'm working with ktinker for the first time. I am currently trying to create a program that follows this order:
open a map in matplotlib
a popup window is called for users to enter in information
when the user clicks on the map grid the coordinates and user
info are stored in a dictionary
matplotlib generates a plot point on the location
The trouble is, when I call the popup window I have written in tkinter, calling the mainloop() function breaks the matplotlib window and it wont generate the plot points until the map window is closed.
getting rid of the mainloop fixes it but then means i cant get the data from the popup.
Anyone know how I can stop one from interfering with the other? i have to keep them in separate classes as Im meant to demonstrate modularity in my code.
here is the main code
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import popup1 as ap
__author__ = "k1221169"
__date__ = "$15-Nov-2015 11:29:21$"
markerList = []
xplots = []
yplots = []
desc = ''
title = ''
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))
img = mpimg.imread('overland map 1.png')
imgplot = plt.imshow(img)
plt.ylim(ymax=1)
plt.xlim(xmin=1)
def mrkApnd(a,b):
a.update(b)
print a
markerList.append(a)
def onclick(event):
if spacecheck(event.xdata, event.ydata):
#print markerList[0]['x']
idx = np.abs(xplots - event.xdata).argmin()
print xplots[idx]
for i in markerList:
if xplots[idx] == i['x'] :
print i
#c = i
ap.useroutput(i)
else:
input1 = ap.userinput()
input2 = {'x':event.xdata, 'y':event.ydata}
input1['title'] = title
input1['desc'] = desc
mrkApnd(input1,input2)
drawMarks()
print input1
return markerList
cid = fig.canvas.mpl_connect('button_press_event', onclick)
def drawMarks():
plt.ion()
for i in markerList:
xplots.append(i['x'])
yplots.append(i['y'])
plt.plot(i['x'], i['y'], i['type'])
def spacecheck(x,y):
a = bool
if np.isclose(xplots, x, atol=50.0).any() and np.isclose(yplots, y, atol=50.00).any():
a=True
print 'yes'
return a
plt.draw()
plt.show()
and here is the popup code called from another file
from Tkinter import *
class popup1():
def __init__(self):
pass
def userinput():
pop = Toplevel()
pop.title("marker")
pop.geometry("300x500+200+200")
#string for title
frame = Frame(pop)
entry = Entry(frame)
entry.pack(side = TOP)
frame.pack( padx =20, pady =20)
#radius button for visibility
frame2 = Frame(pop)
selection = StringVar()
radio_1 = Radiobutton(frame2, text = 'Character', variable = selection, value = 'ob')
radio_2 = Radiobutton(frame2, text = 'Item', variable = selection, value = 'or')
radio_3 = Radiobutton(frame2, text='Event', variable = selection, value = 'oy')
radio_1.select()
radio_1.pack(side = LEFT)
radio_2.pack(side = LEFT)
radio_3.pack(side = LEFT)
frame2.pack(padx =30, pady =30)
#radius button for marker type
frame3 = Frame(pop)
visible = bool
check_1 = Checkbutton(frame3, text = 'GM Only', variable = visible, onvalue= True, offvalue= False)
check_1.pack(side = LEFT)
frame3.pack(padx =30, pady =30)
#string for user input
frame4 = Frame(pop)
entry4 = Entry(frame4)
entry4.pack(side = LEFT)
frame4.pack( padx =20, pady =20)
def infoPass():
#info1 = {'title': entry.get(), 'type': selection.get(), 'vis': visible, 'Desc': entry4.get()}
#info.update(info1)
#print info
pop.destroy()
#buttons
label = Label(pop, text="", height=0, width=100)
label.pack()
b = Button(pop, text="Cancel", width=20, command= pop.destroy )
b.pack(side='bottom',padx=5,pady=5)
b2 = Button(pop, text="Save", width=20, command= infoPass )
b2.pack(side='bottom',padx=5,pady=5)
info = {'title': entry.get(), 'type': selection.get(), 'vis': visible, 'desc': entry4.get()}
pop.mainloop()
return info
If i underdstood your question right, then try to add your own loop.
Remove pop.mainloop()
Make the code be a class for a cleaner code
class userinput:
def __init__(self):
#open your window here and style it etc. and:
self.data_sent = False
def infopass(self):
self.data_sent = True
#your infopass code here and
Create your own loop at the end of init:
def __init__(self):
#...
while self.data_sent == False:
root.update()
while data_sent == False:
pop.update()
Call your popup by
mypopup = userinput()
Good luck ;)
This is my code:
from tkinter import *
class Car:
def __init__(self, car_id, name, num_seats, available):
self.car_id = car_id
self.name = name
self.num_seats = num_seats
self.available = available
available_cars.append(self.name)
def hire_car(self):
self.available = False
booked_cars.append(self.name)
available_cars.remove(self.name)
def return_car(self):
self.available = True
booked_cars.remove(self.name)
available_cars.append(self.name)
def display():
pass
class Carlist:
def __init__(self, available_cars):
self.available_cars = available_cars
def addCar():
pass
def displayAvailable():
print(available_cars)
def displayBooked():
print(booked_cars)
booked_cars = []
available_cars = []
Car(1,"Suzuki Van", 2, True)
id2 = Car(2,"Toyota Corolla", 4, True)
id3 = Car(3,"Honda Crv", 4, True)
id4 = Car(4,"Suzuki Swift", 4, True)
id5 = Car(5,"Mitsibishi Airtrek", 4, True)
id6 = Car(6,"Nissan DC Ute", 4, True)
id7 = Car(7,"Toyota Previa", 7, True)
Car.hire_car(id3)
Carlist.displayAvailable()
Carlist.displayBooked()
#Interface Code
root = Tk()
root.title("Car Booking System")
frameTop = Frame(root)
frameLeft = Frame(root)
frameRight = Frame(root)
frameBottom = Frame(root)
#Top
topLabel = Label(frameTop, text = "Car Booking System", font = 20).pack()
#Right Side
bookLabel = Label(frameRight, text = "Book:").pack()
varSelectedCar = StringVar()
varSelectedCar.set(available_cars[0])
optionHire = OptionMenu(frameRight, varSelectedCar, *available_cars).pack()
buttonHireCar = Button(frameRight, text = "Enter", command = Car.hire_car).pack()
#Left Side
returnLabel = Label(frameLeft, text = "Return:").pack()
varSelectedCar2 = StringVar()
varSelectedCar2.set(booked_cars[0])
optionReturn = OptionMenu(frameLeft, varSelectedCar2, *booked_cars).pack()
buttonHireCar2 = Button(frameLeft, text = "Enter", command = Car.hire_car).pack()
#Bottom
summaryLabel = Label(frameBottom, text = "Summary:").pack()
#INITIALISATION
frameTop.pack(side = TOP)
frameLeft.pack(side = LEFT)
frameRight.pack(side = RIGHT)
frameBottom.pack(side = BOTTOM)
root.mainloop()
I am trying to link the lists to the GUI interface so when enter is clicked it either runs hire_car or return_car and adds their name to the relevant list. Any idea how to do this? Help would be much appreciated.
The overall idea is to have a program which can book and return cars and as a summary at the bottom....
Although this site is not to make other's homework, you got lucky today. However, please try to figure out how it works. How to update OptionMenu info is from HERE.
from collections import namedtuple
from tkinter import *
Car = namedtuple('Car', 'name num_seats')
class CarList:
ID = 0
def __init__(self):
self.cars, self.hired = {}, set()
def add_car(self, car):
self.cars[self.ID] = car
self.ID += 1
def available_cars(self):
'''Returns the list of (id, Car) tuples sorted by Car.'''
return sorted(((car, id)
for id, car in self.cars.items()
if id not in self.hired))
#staticmethod
def labels(cars_seq):
return ['{} [{}]'.format(t[0].name, t[1])
for t in cars_seq]
def hire_car(self, id):
if id in self.hired:
raise ValueError('That car is already hired.')
self.hired.add(id)
def hired_cars(self):
return sorted(((self.cars[id], id)
for id in self.hired))
def return_car(self, id):
if id not in self.hired:
raise ValueError('That car is not even hired.')
self.hired.remove(id)
def add_car(car):
if not isinstance(car, Car):
raise TypeError('Invalid car object.')
carlist.add_car(car)
update_optionmenus()
def hire_car():
label = opt_hire.var.get()
if label:
id = int(label.rsplit(maxsplit=1)[-1][1:-1])
carlist.hire_car(id)
update_optionmenus()
def return_car():
label = opt_return.var.get()
if label:
id = int(label.rsplit(maxsplit=1)[-1][1:-1])
carlist.return_car(id)
update_optionmenus()
def _update_optionmenu(opt_menu_widget, car_seq):
cars = carlist.labels(car_seq)
if cars:
opt_menu_widget.var.set(cars[0])
else:
opt_menu_widget.var.set('')
opt_menu_widget['menu'].delete(0, END)
for lab in cars:
opt_menu_widget['menu'].add_command(label=lab,
command=lambda lab=lab: opt_menu_widget.var.set(lab))
def update_optionmenus():
_update_optionmenu(opt_hire, carlist.available_cars())
_update_optionmenu(opt_return, carlist.hired_cars())
# You have to initiate a carlist to make it work.
carlist = CarList()
#Interface Code
root = Tk()
root.title('Car Booking System')
frame_top = Frame(root)
frame_top.pack(side = TOP)
frame_left = Frame(root)
frame_left.pack(side = LEFT)
frame_right = Frame(root)
frame_right.pack(side = RIGHT)
frame_bottom = Frame(root)
frame_bottom.pack(side = BOTTOM)
#Top
label_top = Label(frame_top, text = 'Car Booking System',
font = 20).pack()
#Right Side
label_hire = Label(frame_right, text = 'Book:', width=25).pack()
gui_var_hire = StringVar()
opt_hire = OptionMenu(frame_right, gui_var_hire, 'anything')
opt_hire.var = gui_var_hire
del gui_var_hire
opt_hire.pack()
button_hire = Button(frame_right, text = 'Enter',
command = hire_car).pack()
#Left Side
label_return = Label(frame_left, text = 'Return:', width=25).pack()
gui_var_return = StringVar()
opt_return = OptionMenu(frame_left, gui_var_return, 'anything')
opt_return.var = gui_var_return
opt_return.pack()
del gui_var_return
button_return = Button(frame_left, text = 'Enter',
command = return_car).pack()
#Bottom
label_summary = Label(frame_bottom, text = 'Summary:').pack()
add_car(Car('Suzuki Van', 2))
add_car(Car('Toyota Corolla', 4))
add_car(Car('Honda Crv', 4))
add_car(Car('Suzuki Swift', 4))
add_car(Car('Mitsibishi Airtrek', 4))
add_car(Car('Nissan DC Ute', 4))
add_car(Car('Toyota Previa', 7))
add_car(Car('Honda Crv', 2))
root.mainloop()
what i have is a window that opens up and it has a list box. this is created using one class. when i click the search button and results are found using a different class, i want the list box to update without having to open up another window. below is my code so far\n
from Tkinter import *
class addTask:
def __init__(self):
self.addWindow = Tk()
self.addWindow.configure(background = "black")
self.addWindow.geometry("450x450")
self.addWindow.resizable(width = False, height = False)
self.addWindow.title("Add Task")
self.addNameLabel = Label(self.addWindow,text="Add the name of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addNameLabel.place(relx=0.01, rely=0.05)
self.nameWiget = Text (self.addWindow, width = 63, height = 1)
self.nameWiget.place(relx=0.0, rely=0.1)
self.addDateLabel = Label(self.addWindow,text="Add the date of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addDateLabel.place(relx=0.01, rely=0.2)
self.dateWiget = Text (self.addWindow, width = 63, height = 1)
self.dateWiget.place(relx=0.0, rely=0.25)
self.addTaskLabel = Label(self.addWindow,text="Add the details of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addTaskLabel.place(relx=0.01, rely=0.35)
self.taskWiget = Text (self.addWindow, width = 63, height = 1)
self.taskWiget.place(relx=0.0, rely=0.4)
addButton = Button(self.addWindow,height = 5, width = 20, text="Add Task",highlightbackground="black",font=("Helvetica",10,"bold"),command=lambda:self.saveFuntion())
addButton.place(relx=0.25, rely=0.55)
def saveFuntion(self):
nameInfo = (self.nameWiget.get(1.0, END))
dateInfo = self.dateWiget.get(1.0, END)
taskInfo = self.taskWiget.get(1.0, END)
print nameInfo
task1 = Task(nameInfo,dateInfo,taskInfo)
task1.save()
self.nameWiget.delete(1.0,END)
class Task:
def __init__(self,name,date,task):
self.__name = name
self.__date = date
self.__task = task
def save(self):
fileName = open("dataFile.txt","a")
fileName.write(self.__name)
fileName.write(self.__date)
fileName.write(self.__task)
class editTask:
def __init__(self):
self.editWindow = Tk()
self.newWindow = Tk()
self.newWindow.geometry("450x750")
self.editWindow.configure(background = "black")
self.editWindow.geometry("450x750")
self.editWindow.resizable(width = False, height = False)
self.editWindow.title("Edit Task")
self.listBox = Listbox(self.editWindow,heigh = 15, width = 30)
self.listBox.place(relx = 0.2, rely = 0.6)
#drop down menu
self.var = StringVar(self.editWindow)
self.var.set("Select search critria")
self.choices = ["Name","Date"]
self.option = OptionMenu(self.editWindow,self.var,*self.choices)
self.option.configure(bg = "black")
self.option.place(relx = 0.5, rely = 0.2)
#edit label and text box
self.editLabel = Label(self.editWindow,text="Add the name of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.editLabel.place(relx=0.01, rely=0.05)
self.editInfoWiget = Text (self.editWindow, width = 63, height = 1)
self.editInfoWiget.place(relx=0.0, rely=0.1)
# search button
searchButton = Button(self.editWindow,height = 5, width = 20, text="Search for Task",highlightbackground="black",font=("Helvetica",10,"bold"),command=lambda:self.searchFuntion())
searchButton.place(relx=0.3, rely=0.4)
def searchFuntion(self):
critria = self.var.get()
info = self.editInfoWiget.get(1.0,END)
thing = info.split("\n")
thing2 = thing[0]
search = searchCritria(critria,thing2)
search.search()
# def openListBox(self):
class searchCritria():
def __init__(self,critria,info):
self.__critria = critria
self.__info = info
def search(self):
self.file = open("dataFile.txt", "r+")
fileData = self.file.readlines()
self.file.close()
lengthOfFile = len(fileData)
counter = 1
self.name = []
self.date = []
self.details = []
for i in range (lengthOfFile):
split = fileData[i].split("\n")
while counter == 1:
self.name.append(split)
break
while counter == 2:
self.date.append(split)
break
while counter == 3:
self.details.append(split)
break
counter = counter +1
if counter > 3:
counter = 1
if self.__critria == "Name":
for x in range (len(self.name)):
self.taskName = self.name[x]
self.taskName2 = self.taskName[0]
if self.__info == self.taskName2:
openWindow = True
else :
openWindow = False
if openWindow == True:
editTask().listBox.insert(END,self.taskName2)
if self.__critria == "Date":
for x in range (len(self.date)):
self.taskDate = self.date[x]
self.taskDate2 = self.taskDate[0]
if self.__info == self.taskDate2:
print "found"
else :
print"not found"
class editTask2():
def __init__(self):
self.edit2Window = Tk()
self.edit2Window.configure(background = "black")
self.edit2Window.geometry("450x350")
self.edit2Window.resizable(width = False, height = False)
self.edit2Window.title("Edit Task")
any help would be great
thanks
The biggest problem in your code is that you're creating multiple instances of Tk. Tkinter simply isn't designed to work that way. You should only ever create a single instance of Tk. If you need additional windows, create instances of Toplevel.
Also, you need to call the mainloop function of this instance of Tk exactly once. Without it, your GUI will not work.
If you want to update a listbox in another class than where it was created, the concept is pretty simple: if A needs to update B, A needs a reference to B. So, either pass in a reference to the listbox when you create the other class, or give the other class a method you can call where you pass in the reference to the listbox after it was created.