I am new to Tkinter. I'd like to write simple program and organize it using pack() method. Here is my code:
import Tkinter as tk
from Tkinter import *
import xlrd, os, sys, json
class Main():
def __init__(self):
global col, col1
self.master = tk.Tk()
self.master.title("Zliczanie ilosci spraw")
self.master.minsize(width=800, height=600)
plik = 'Aktualnie wybrany plik to: ' + 'Rejestr'
text = Label(self.master, text = plik)
text.pack(pady = 20)
self.wyswietlanie()
def wyswietlanie(self):
'''Funkcja, ktora zlicza i wyswietla ilosc spraw pracownikow'''
policzone_1 = []
policzone_2 = []
z = 0
dzial1 = {
"Pracownik1": "PRAC1",
"Pracownik2": "PRAC2"}
dzial2 = {
"Pracownik12": "PRAC12",
"Pracownik22": "PRAC22"}
for nazw in dzial1:
x = dzial1[nazw] #nazwisko z pliku excela
nazwisko = 0
policzone_1.append((nazw, nazwisko))
for nazw in dzial2:
x = dzial2[nazw] #nazwisko z pliku excela
nazwisko = 0
policzone_2.append((nazw, nazwisko))
posortowane1 = sorted(policzone_1,key=lambda x:x[1], reverse=True)
posortowane2 = sorted(policzone_2,key=lambda x:x[1], reverse=True)
dzial3 = Label(self.master)
dzial3.pack(side = LEFT)
dzial4 = Label(self.master)
dzial4.pack(side = LEFT)
for i in posortowane1:
wynik = '%s: %s' % (i[0], i[1])
dzial1 = Label(self.master, text = wynik, font = "Verdana 10 bold")
dzial1.pack(in_ = dzial3, padx = 200)
for i in posortowane2:
wynik = '%s: %s' % (i[0], i[1])
dzial2 = Label(self.master, text = wynik)
dzial2.pack(in_ = dzial4, padx = 200)
def run(self):
self.master.mainloop()
glowne = Main()
glowne.run()
Result is as on image below:
Why dzial1 and dzial2 are in these places (far from "text")? How can I organize dzial1, dzial2 (set them closer to each other)?
Related
Iam complete new to python,
this code i've been following steps from a book "python GUI programing cookbook "
the GUI works fine , but the methods wont work please help :
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as mBox
from tkinter import Spinbox
class OOP:
def __init__(self):
self.win=tk.Tk()
self.win.title("silver and gold")
self.win.iconbitmap(r'E:\hydra-logo.ico')
self.GUI()
def click_me(self):
self.action.configure(text = "item has been added-- "+ self.matrial.get()+self.weight.get())
def quit(self):
self.win.quit()
self.win.destroy()
exit()
def msgbox(self):
answer=mBox.askyesno('','are you satisfied ? ')
if answer==True:
print("+1 satisfied ")
else:
print("+1 unsatisfied ")
def spin(self):
value= self.spin.get()
print(value)
self.scr.insert(tk.INSERT,value+'\n')
def GUI(self):
tabcontrol=ttk.Notebook(self.win)
tab1=ttk.Frame(tabcontrol)
tabcontrol.add(tab1,text = 'Entry')
tab2=ttk.Frame(tabcontrol)
tabcontrol.add(tab2,text = "Storage")
tab3=ttk.Frame(tabcontrol)
tabcontrol.add(tab3,text = "customers")
tab3=tk.Frame(tab3,bg = 'blue')
tab3.pack()
tabcontrol.pack(expand = 1,fill = "both")
safezone=ttk.LabelFrame(tab1,text = 'my comfort zone')
safezone.grid(column = 0,row = 0)
mBox.showinfo('',"Running ")
## my safe zone
storage=ttk.LabelFrame(tab2,text = 'your storage is here')
storage.grid(column = 0,row = 0)
for orangecolor in range(2):
canvas=tk.Canvas(tab3,width = 150,height = 80,highlightthickness = 0,bg = 'orange')
canvas.grid(row = orangecolor,column = orangecolor)
menuBar=Menu(self.win)
self.win.config(menu = menuBar)
fileMenu=Menu(menuBar,tearoff = 0)
HelpMenu=Menu(menuBar,tearoff = 0)
menuBar.add_cascade(label = "File",menu = fileMenu)
menuBar.add_cascade(label = "Help",menu = HelpMenu)
HelpMenu.add_command(label = "About",command = self.msgbox)
fileMenu.add_command(label = "New")
fileMenu.add_command(label = "Exit",command = quit)
fileMenu.add_checkbutton(label = "Night Mode")
labelsFrame=ttk.LabelFrame(storage,text = "made by essam")
labelsFrame.grid(column = 0,row = 9,padx = 10,pady = 0)
ttk.Label(safezone,text = "Choose a metal: ").grid(column = 0,row = 0)
ttk.Label(safezone,text = "type the weight: ").grid(column = 1,row = 0,sticky = 'W')
weight=tk.StringVar()
wightEntered=ttk.Entry(safezone,width = 12,textvariable = weight)
wightEntered.grid(column = 1,row = 1)
wightEntered.focus()
matrial=tk.StringVar()
matrialEntered=ttk.Combobox(safezone,width = 12,textvariable = matrial,state = 'readonly')
matrialEntered.grid(column = 0,row = 1)
matrialEntered [ 'values' ]=("Gold","silver")
matrialEntered.current(0)
action=ttk.Button(safezone,text = "add ",command = self.click_me)
action.grid(column = 4,row = 1)
radVar=tk.IntVar()
radVar.set(99)
colors=[ "blue","gold","red" ]
spin=Spinbox(safezone,values = (1,2,4,42,100),width = 5,borderwidth = 20,
relief = tk.SUNKEN,command = self.spin)
spin.grid(column = 2,row = 1)
scrolW=30
scrolH=3
scr=scrolledtext.ScrolledText(safezone,width = scrolW,height = scrolH,wrap = tk.WORD)
scr.grid(column = 0,columnspan = 5,row = 7)
#******
oop =OOP()
oop.win.mainloop()
Okay so I wrote this code...
#!/usr/bin/env
import sys
import time
import subprocess
from Tkinter import *
import numpy
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
import matplotlib.pyplot as plt
import threading
CDatei = subprocess.Popen("/home/pi/meinc++/Spi")
print("Hallo")
i = 0
x = 0
def GetValue():
with open("/home/pi/meinc++/BeispielDatei.txt","r") as Datei:
for line in Datei:
time.sleep(0.01)
return line
def WithoutNull(input):
ReturnValue = input
while ReturnValue is None:
ReturnValue = GetValue()
return ReturnValue
def UebergabeWert():
while x == 0:
WholeString = WithoutNull(GetValue())
StringVar, DatumVar = WholeString.strip().split(' - ')
IntStringVar = [int(v) for v in StringVar.split()]
return IntStringVar, DatumVar
def MinutenWert():
Maximum = 0
Minimum = 0
i = 0
LaengeArray = 0
Multiplikator = 10000
ArrayValue = [-999999]*Multiplikator
AlteZeit = time.time()
while 1:
CompleteValue, Trash = UebergabeWert()
ArrayValue[i] = CompleteValue[0]
i = i + 1
ArrayFilter = filter(lambda c: c != -999999,ArrayValue)
ArraySumme = numpy.sum(ArrayFilter)
LaengeArray = len(ArrayFilter)
Mittelwert = ArraySumme/LaengeArray
ArraySortierung = sorted(ArrayFilter)
Maximum = ArraySortierung[LaengeArray-1]
Minimum = ArraySortierung[0]
NeueZeit = time.time()
if NeueZeit-AlteZeit >= 60:
AlteZeit = time.time()
ArrayValue[i:Multiplikator] = [-999999]*(Multiplikator-i)
i = 0
yield Mittelwert
yield Maximum
yield Minimum
yield LaengeArray
yield ArrayFilter
def UebergabeTkinter():
while 1:
Mittelwert = next(MinutenWertYield)
Maximum = next(MinutenWertYield)
Minimum = next(MinutenWertYield)
LaengeArray = next(MinutenWertYield)
ArrayFilter = next(MinutenWertYield)
CompleteValue, DatumVar = UebergabeWert()
Variable1.set(CompleteValue[0])
Variable2.set(CompleteValue[1])
Variable3.set(CompleteValue[2])
Variable4.set(CompleteValue[3])
VariableMittelwert.set(Mittelwert)
VariableMaximum.set(Maximum)
VariableMinimum.set(Minimum)
t = threading.Thread(target = Grafik)
t.start()
root.update()
def Grafik():
GrafikAnfang = time.time()
Array = 0
ArrayGrafik = [0]*20
GrafikEnde = 1
while 1:
CompleteValue, DatumVar = UebergabeWert()
ArrayGrafik[Array] = CompleteValue[0]
LaengeArrayGrafik = len(ArrayGrafik)
fig = Figure(figsize = (3, 3))
axis = fig.add_subplot(111)
axis.legend()
axis.grid()
canvas = FigureCanvasTkAgg(fig, master = root)
canvas.get_tk_widget().grid(row=10,column=0,rowspan=2,columnspan=2)
LinienBreite = numpy.linspace(1,LaengeArrayGrafik,LaengeArrayGrafik)
axis.plot(LinienBreite,ArrayGrafik,'b-')
axis.set_xticks(LinienBreite)
DatumArray = [DatumVar]
axis.set_xticklabels(DatumArray)
canvas.draw()
fig.clear()
print Array
if GrafikEnde-GrafikAnfang < 600:
Array = Array + 1
GrafikEnde = time.time()
if GrafikEnde-GrafikAnfang >= 600:
del ArrayGrafik[0]
def Exit():
root.destroy()
return
try:
MinutenWertYield = MinutenWert()
root = Tk()
Leiste = Menu(root)
root.config(menu = Leiste)
DateiMenu = Menu(Leiste)
Leiste.add_cascade(label = "datei", menu = DateiMenu)
DateiMenu.add_command(label = "Exit", command = Exit)
EditMenu = Menu(Leiste)
Leiste.add_cascade(label = "edit", menu = EditMenu)
Variable1 = IntVar()
Variable2 = IntVar()
Variable3 = IntVar()
Variable4 = IntVar()
VariableMittelwert = IntVar()
VariableMaximum = IntVar()
VariableMinimum = IntVar()
Ausgang = 0
for column in range(0,8,2):
String1 = "Ausgang "
String1 += `Ausgang`
Ausgang = Ausgang + 1
Label(text = String1).grid(row=0,column=column)
Ausgang = 0
for column in range(0,8,2):
String1 = "Der Wert von "
String2 = " ist: "
String1 += `Ausgang`
Ausgang = Ausgang + 1
String3 = String1+String2
Label(text = String3).grid(row=2,column=column)
Label(text = "Der Mittelwert ist: ").grid(row=4,column=0)
Label(text = "Das Maximum ist: ").grid(row=5,column=0)
Label(text = "Das Mimimum ist: ").grid(row=6,column=0)
Label1 = Label(root, textvariable = Variable1)
Label1.grid(row = 2, column = 1)
Label2 = Label(root, textvariable = Variable2)
Label2.grid(row = 2, column = 3)
Label3 = Label(root, textvariable = Variable3)
Label3.grid(row = 2, column = 5)
Label4 = Label(root, textvariable = Variable4)
Label4.grid(row = 2, column = 7)
LabelMittelwert = Label(root, textvariable = VariableMittelwert)
LabelMittelwert.grid(row = 4, column = 1)
LabelMaximum = Label(root, textvariable = VariableMaximum)
LabelMaximum.grid(row = 5, column = 1)
LabelMinimum = Label(root, textvariable = VariableMinimum)
LabelMinimum.grid(row = 6, column = 1)
UebergabeTkinter()
print "Hallo"
root.mainloop()
except KeyboardInterrupt:
CDatei.kill()
root.quit()
root.destroy()
and when i run it, it says "RuntimeError: main thread is not in the main loop".
Short explanation of the code: It's a code to read out sensor data from a text file -
GetValue().
If the Data is Null it'll read out again - WithoutNull().
The Data is then splitted into data and timestamp (cause it has the format val1, val2, val3, val4, time) - UebergabeWert.
Then the maxima, minima and average of the data will be measured - MinutenWert()
After this, the values are set as labels and go their way into Tkinter - UebergabeTkinter()
The Tkinter build is mainly in Try:
What I wanted to do there, is to implement a graph to Tkinter, but because of the fast changing values it got tremendously slow so i decided to put the graph build in a thread and run it parallel to Tkinter. Unfortunately, it doesn't seem to work and I don't know why
Any suggestions?
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()
I want to display the values in the text boxes, but i'm getting this error:
blue.set(B_mean1)
AttributeError: 'numpy.ndarray' object has no attribute 'set'
and my code is:
from Tkinter import Tk, Frame, BOTH
from Tkinter import *
import cv2
from collections import *
from CBIR import *
from experiment import *
from scipy.spatial import distance
import Tkinter,tkFileDialog
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent,background="light grey")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("PISE")
self.pack(fill=BOTH, expand=1)
def open():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
custName.set(path)
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.place(x = 100, y = 100)
graylist1 = list()
resizelist1 = list()
eq_graylist1 = list()
cont_list1 = list()
ene_list1 = list()
homo_list1 = list()
cor_list1 = list()
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
dis_list1 = list()
imge = cv2.imread(path)
arr = array(imge)
g_img = cv2.imread(path,0)
gray_re_img = cv2.resize(g_img,(256,256))
graylist1.append(gray_re_img)
equ = cv2.equalizeHist(gray_re_img)
eq_graylist1.append(equ)
re_img = cv2.resize(imge,(256,256))
resizelist1.append(re_img)
blue, green, red = cv2.split(re_img)
total = re_img.size
B = sum(blue) / total
G = sum(green) / total
R = sum(red) / total
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
im = skimage.io.imread(path, as_grey=True)
im = skimage.img_as_ubyte(im)
im /= 32
g = skimage.feature.greycomatrix(im, [1], [0], levels=8, symmetric=False, normed=True)
cont = skimage.feature.greycoprops(g, 'contrast')[0][0]
cont_list1.append(cont)
ene = skimage.feature.greycoprops(g, 'energy')[0][0]
ene_list1.append(ene)
homo = skimage.feature.greycoprops(g, 'homogeneity')[0][0]
homo_list1.append(homo)
cor = skimage.feature.greycoprops(g, 'correlation')[0][0]
cor_list1.append(cor)
dis = skimage.feature.greycoprops(g, 'dissimilarity')[0][0]
dis_list1.append(dis)
feature_matrix_ip = zip( B_mean1 , G_mean1 , R_mean1, cont_list1 , ene_list1 , homo_list1 , cor_list1 , dis_list1)
blue.set(B_mean1)
root = Tk()
root.geometry("1105x605+300+300")
app = Example(root)
label = Label(app, text='Python Image Search', fg = 'black',font = 'PoorRichard 24')
label.pack()
label.place(y = 5, x = 0)
img = Image.open('logo.png')
bg_img = ImageTk.PhotoImage(img)
label1 = Label(app, image = bg_img)
label1.place(y = 5, x = 1225)
custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.grid(column=0,row=0,sticky='EW')
yourName.update()
yourName.focus_set()
yourName.pack(padx = 20, pady = 20,anchor='n')
yourName.place(y = 60, x = 100, width = 525, height = 25)
blue_label = Label(app,text = 'Blue Mean')
blue_label.place(x = 850,y = 140)
blue = IntVar()
blue_text = Entry(app,textvariable = blue)
blue_text.place(x = 1000,y = 140)
button = Button(app, text='Select an Image',command = open)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 650, y = 60)
root.mainloop()
All I want to know is how to display the values into the textbox. Any suggestions are welcome.
Thanks in advance!
Your problem is that you are using the variable name blue for two different things. At one point it's a numpy array and at another it is an IntVar. When you call blue.set(...), you are doing that at the point where blue references a numpy array, hence the error message 'numpy.ndarray' object has no attribute 'set'
Try changing the name of your IntVar to something else, such as blue_var, and make sure you change it everywhere.
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).