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()
Related
I have a text file with values that I need to display in a scroll box tkinter. I have been succesful in doing this but there is a problem. When I press submit to add more values to my text file in my program, the scrollbox displaying the contents in the text file does not update with the new values.
Here is a screenshot of the program:
This is my text file:
amazon.com
username#gmail.com
n3*F/X"qse~a`_+
netflix.com
username#outlook.com
avOmCl|Jb?O<
apple.com
username#icloud.com
s=DT8n*Y"y
However when I press submit the text file updates with the values submitted but the scrollbox does not.
Here is my full code:
import string
import random
from tkinter import *
import tkinter.scrolledtext as st
mypasslist = []
with open("password&usernames.txt", "r") as input:
for line in input:
items = line.split()
mypasslist.append([item for item in items[0:]])
def generatePassword():
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(random.choice(characters) for x in range(random.randint(8, 16)))
return password
def writeToFile(input_variable):
with open("password&usernames.txt", "a") as input:
input.writelines(input_variable)
top = Tk()
top.geometry("1920x1080")
def ifSubmit():
global a
a = generatePassword()
label1 = Label(top, text='Your password is: %s' % a, font=("Arial", 11)).place(x = 40, y = 170)
label1 = Label(top, justify='left', text='Your password and username has been saved, you can access them below.').place(x = 40, y = 227)
copy_button = Button(top, text = 'Copy', command=copyText).place(x=40, y=195)
service = service_var.get()
username = username_var.get()
writeToFile('%s\n' % str(service))
writeToFile('%s\n' % str(username))
writeToFile('%s\n' % str(a))
writeToFile('\n')
def copyText():
top.clipboard_clear()
top.clipboard_append(a)
top.update()
# the label for user_name
Service = Label(top, text = "Service").place(x = 40, y = 60)
user_name = Label(top, text = "Username").place(x = 40, y = 100)
submit_button = Button(top, text = "Submit", command=ifSubmit)
submit_button.place(x = 40, y = 130)
service_var = StringVar()
Service_input_area = Entry(top, width = 30, textvariable=service_var)
Service_input_area.place(x = 110, y = 60)
service = service_var.get()
username_var = StringVar()
user_name_input_area = Entry(top, width = 30, textvariable=username_var)
username = username_var.get()
user_name_input_area.place(x = 110, y = 100)
text_area = st.ScrolledText(top, width = 50, height = 10)
text_area.grid(column = 0, pady = 260, padx = 40)
for i in mypasslist:
text_area.insert(INSERT, i)
text_area.insert(INSERT, '\n')
text_area.configure(state ='disabled')
top.mainloop()
So how could I make the program update every time new values have been submitted?
I got it working, I had to do:
def writeToFile(input_variable):
with open("password&usernames.txt", "a") as input:
input.writelines(input_variable)
text_area['state'] = NORMAL
text_area.insert(INSERT, input_variable)
text_area['state'] = DISABLED
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?
I am having a problem with adding status bar at the bottom of my program. When I do status.pack() it gives me this error : _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack. In My (
def init(self): ) If I delete (self.grid(sticky = W+E+N+S) then the window pops up an then the status bar is on the window, but then the rest of the program isn't there. I was wondering if someone give some insight on how to fix this
from tkinter.constants import END
from tkinter import ttk
from tkinter import *
from tkinter import font
from tkinter import messagebox
import tkinter as tk
import turtle
import random
from tkinter import filedialog
from PIL import Image
class App(Frame):
**********************************************************************************************************************************************************************************************************************8888
'''The code below Creates a Menu Bar across the top of the window '''
App = Tk()
menu = Menu (App)
App.config(menu = menu)
'''Lines 20 - 22 are basic setup for drop down meun box at the top of the page.'''
fileMenu = Menu(menu, tearoff = 0)
fileMenu.add_command(label = "New Project", command = turtle)
fileMenu.add_command(label = "Open", command = turtle)
fileMenu.add_command(label = "Save", command = turtle)
fileMenu.add_command(label = "Save as", command = turtle)
fileMenu.add_command(label = "Close", command = turtle)
menu.add_cascade(label = "File", menu = fileMenu)
fileMenu.add_separator()
'''This bit of code adds a separator between the buttons on the drop down menu.'''
fileMenu.add_command(label = "Exit", command = App.quit)
editMenu = Menu(menu, tearoff = 0)
editMenu.add_command(label = "Cut", command = turtle)
editMenu.add_command(label = "Copy", command = turtle)
editMenu.add_command(label = "Paste", command = turtle)
editMenu.add_command(label = "Delete", command = turtle)
editMenu.add_command(label = "Select All", command = turtle)
menu.add_cascade(label = "Edit", menu = editMenu)
helpMenu = Menu(menu, tearoff = 0)
helpMenu.add_command(label = "Help Index", command = turtle)
helpMenu.add_command(label = "About", command = turtle)
menu.add_cascade(label = "Help", menu = helpMenu)
************************************************************************************************************************************************************************************************************************************
''' The code below creates a Status Bar Across the bottom of the page. '''
status = Label(App, text = "This is a status bar...", bd = 1, relief = SUNKEN, anchor = W)
status.pack()
******************************************************************************************************************************************************************************************************************************
def __init__(self):
'''Sets up the window and widgets.'''
Frame.__init__(self, bg = "white" ) #this sets the background color of the window.
self.master.title("Auto Body Buddy Estimator") #this is the title of the screen
self.master.geometry("600x600") #this is the specs for the window size
self.master.resizable(0, 0) #this makes the window none resizable
self.master.columnconfigure(0, weight = 1)
self.master.rowconfigure(0, weight = 1)
self.grid(sticky = W+E+N+S)
#!/usr/bin/python
'''import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = ('The file "' + fn + '" was uploaded successfully')
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,) '''
***********************************************************************************************************************************************************************
''' Creates the nested frame for the Data pane for the image '''
self._dataPane1 = Frame(self)#, bg = "orange")
self._dataPane1.grid(row = 0, column = 0)
self._pictureImage = PhotoImage(file = "../logo.gif")
self._imageLabel = Label(self._dataPane1, image = self._pictureImage)
self._imageLabel.grid(row = 0, column= 0)
*********************************************************************************************************************************************************************
''' Creates the nested frame for the Data pane'''
self._dataPaneEntryInfo = Frame(self, bg = "white")
self._dataPaneEntryInfo.grid(row = 1, column = 0)
''' Label and field for First Name '''
self._firstNameLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "First Name ")
self._firstNameLabel.grid(row = 0, column = 0)
self._firstNameVar = DoubleVar()
self._firstNameEntry = Entry(self._dataPaneEntryInfo, textvariable = self._firstNameVar)
self._firstNameEntry.grid(row = 0, column = 1)
''' Label and field for Last Name '''
self._LastNameLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Last Name ")
self._LastNameLabel.grid(row = 1, column = 0)
self._LastNameVar = DoubleVar()
self._LastNameEntry = Entry(self._dataPaneEntryInfo, textvariable = self._LastNameVar)
self._LastNameEntry.grid(row = 1, column = 1)
''' Label and field for Phone Number '''
self._phoneNumberLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Phone Number ")
self._phoneNumberLabel.grid(row = 2, column = 0)
self._phoneNumberVar = DoubleVar()
self._phoneNumberEntry = Entry(self._dataPaneEntryInfo, textvariable = self._phoneNumberVar)
self._phoneNumberEntry.grid(row = 2, column = 1)
''' Label and field for Email '''
self._EmailLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Email Address ")
self._EmailLabel.grid(row = 3, column = 0)
self._EmailVar = DoubleVar()
self._EmailEntry = Entry(self._dataPaneEntryInfo, textvariable = self._EmailVar)
self._EmailEntry.grid(row = 3, column = 1)
''' Label and field for Address '''
self._addressLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Address \n (OPITIONAL) ")
self._addressLabel.grid(row = 4, column = 0)
self._addressVar = DoubleVar()
self._addressEntry = Entry(self._dataPaneEntryInfo, textvariable = self._addressVar)
self._addressEntry.grid(row = 4, column = 1)
*********************************************************************************************************************************************************************
''' Label and field for Year of the Car '''
self._yearLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Year ")
self._yearLabel.grid(row = 0, column = 2)
self._yearVar = DoubleVar()
self._yearEntry = Entry(self._dataPaneEntryInfo, textvariable = self._yearVar)
self._yearEntry.grid(row = 0, column = 3)
''' Label and field for Make of the Car '''
self._makeLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Make ")
self._makeLabel.grid(row = 1, column = 2)
self._makeVar = DoubleVar()
self._makeEntry = Entry(self._dataPaneEntryInfo, textvariable = self._makeVar)
self._makeEntry.grid(row = 1, column = 3)
''' Label and field for Model of the Car '''
self._modelLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Model ")
self._modelLabel.grid(row = 2, column = 2)
self._modelVar = DoubleVar()
self._modelEntry = Entry(self._dataPaneEntryInfo, textvariable = self._modelVar)
self._modelEntry.grid(row = 2, column = 3)
''' Label and field for Package of the Car '''
self._packageLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Package ")
self._packageLabel.grid(row = 3, column = 2)
self._packageVar = DoubleVar()
self._packageEntry = Entry(self._dataPaneEntryInfo, textvariable = self._packageVar)
self._packageEntry.grid(row = 3, column = 3)
''' Label and field for VIN # of the Car '''
self._vinLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "VIN # ")
self._vinLabel.grid(row = 4, column = 2)
self._vinVar = DoubleVar()
self._vinEntry = Entry(self._dataPaneEntryInfo, textvariable = self._vinVar)
self._vinEntry.grid(row = 4, column = 3)
******************************************************************************************************************************************************************************************************
''' Creates the nested frame for the Data pane'''
self._dataPaneComment = Frame(self, bg = "black")
self._dataPaneComment.grid(row = 2, column = 0)
'''# Label and info field for Comment Box .'''
self._text = "Enter text here. "
self._outputArea = Text(self._dataPaneComment, width = 50, height = 10, wrap = WORD)
self._outputArea.grid(row = 0, column = 0, columnspan = 2)
*********************************************************************************************************************************************************************************************************
''' Creates the nested frame for the Button pane for the Submit'''
self._buttonPane = Frame(self) #this creates a box for the buttons to be placed in one area.
self._buttonPane.grid(row = 3, column = 0)#this gives the button pane a position in the GUI
''' Black and White button '''
self._button1 = Button(self._buttonPane, text = "SUBMIT", command = self._NameEntry)#This creates the button.
self._button1.grid(row = 0, column = 0) #This gives the button a position in the GUI.
********************************************************************************************************************************************************************************************************
def _NameEntry(self):
open("Results.txt", "w").close()
first = self._firstNameEntry.get()
last = self._LastNameEntry.get()
phone = self._phoneNumberEntry.get()
email = self._EmailEntry.get()
address = self._addressEntry.get()
year = self._yearEntry.get()
make = self._makeEntry.get()
model = self._modelEntry.get()
package = self._packageEntry.get()
vin = self._vinEntry.get()
with open("../" + first + " " + last + ".txt", "a") as the_file:
the_file.write("First Name: " + first + "\n" "Last Name: " + last + "\n" "Phone Number: " + phone + "\n" "Email: " + email + "\n"
"Address: " + address + "\n" "Year: " + year + "\n" "Make: " + make + "\n" "Model: " + model + "\n"
"Package: " + package + "\n" "Vin: " + vin + "\n")
'''open("Results.txt", "w").close()
last = self._LastNameEntry.get()
with open("../Results.txt", "a") as the_file:
the_file.write("Last Name: " + last)'''
'''first = self._firstNameEntry.get()
name = open("Results.txt", "w")
name.write("First Name: ".insert(first))
name.close()'''
def main():
'''Instantiate and pop up the window.'''
App().mainloop()
if __name__ == '__main__':
main()
I'm exactly sure on how to upload the gif file with this code.
The error message is telling you what's wrong. If you have already used one geometry manager within a widget you cannot use another.
e.g. - You cannot use both pack and grid within a frame. You must use one or the other.
You could make another widget and then use the seperate geometry manager within this widget but you would have to use the original manager to place it within the master widget.
My function mapupdater isn't working. It seems tkinter isn't keeping a reference to the image. I tried storing the reference in an array, I tried what was suggester here How to update the image of a Tkinter Label widget?
Both don't work.
#-----Begin Global Declarations-----#
global futureonoff
futureonoff = True
#-----End Global Declarations-----#
#Create a new window
window = Tkinter.Tk()
window.wm_title("SpaceMass")
window.geometry("1000x1000")
window.self= Text(bg='black')
window.self.pack(fill="both", expand=True)
#updating map based on ISS location
def mapupdater():
global futureonoff
marker_list = []
timenowforcomputing = strftime("%Y-%m-%d %H:%M:%S", gmtime())
iss.compute(timenowforcomputing)
currentlong = iss.sublong
currentlat = iss.sublat
currentlongfloat= float(iss.sublong)
currentlatfloat= float(iss.sublat)
#convert radians to degrees with the equations 1 radian = 57.2957795 degrees
#TODO Learn how to use pi in python
currentlongfloat = round(currentlongfloat*57.2957795, 3)
currentlatfloat= round(currentlatfloat*57.2957795, 3)
print(currentlongfloat)
print(currentlatfloat)
if futureonoff == True:
futureintermenter = 0
while futureintermenter < len(long_list_3_orbits):
marker_list.append("markers=size:mid|label:F|color:blue|"+str(lat_list_3_orbits[futureintermenter])+","+str(long_list_3_orbits[futureintermenter])+"|")
futureintermenter = futureintermenter + 1
marker_list.append("markers=size:mid|label:S|color:red|"+str(currentlatfloat)+","+str(currentlongfloat)+"|")
toopenupdater = get_static_google_map("mymap2", center="42.950827,-122.108974", zoom=1, imgsize=(500,500), imgformat="gif", maptype="satellite", markers=marker_list)
#Code from https://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint
uupdater = urllib.urlopen(toopenupdater)
raw_data_u = uupdater.read()
u.close()
b64_data_u = base64.encodestring(raw_data_u)
imgtoprint = Tkinter.PhotoImage(data=b64_data)
# from http://www.daniweb.com/software-development/python/threads/79337/putting-an-image-into-a-tkinter-thingy
# pick an image file you have .bmp .jpg .gif. .png
# load the file and covert it to a Tkinter image object
panel1.configure(image = imgtoprint)
panel1.image = imgtoprint
#updata map after 30 seconds
window.after(30000, mapupdater)
def togglemap():
global futureonoff
print(futureonoff)
if futureonoff == True:
futureonoff = False
else:
futureonoff = True
mapupdater()
print(futureonoff)
#text_file.configure(text=testing)
#Info about buttons http://effbot.org/tkinterbook/button.htm
#Parsing code from https://stackoverflow.com/questions/773797/updating-tkinter-labels-in-python
#settings for font, font size, pixel size, of the text in our GUI
#convert radians to degrees with the equations 1 radian = 57.2957795 degrees
#TODO Learn how to use pi in python
currentlongfloat = round(currentlongfloat*57.2957795, 3)
currentlatfloat= round(currentlatfloat*57.2957795, 3)
if futureonoff == True:
futureintermenter = 0
while futureintermenter < len(long_list_3_orbits):
marker_list.append("markers=size:mid|label:F|color:blue|"+str(lat_list_3_orbits[futureintermenter])+","+str(long_list_3_orbits[futureintermenter])+"|")
futureintermenter = futureintermenter + 1
marker_list.append("markers=size:mid|label:S|color:red|"+str(currentlatfloat)+","+str(currentlongfloat)+"|")
#places map into GUI
toopen = get_static_google_map("mymap2", center="42.950827,-122.108974", zoom=1, imgsize=(500,500), imgformat="gif", maptype="satellite", markers=marker_list)
#im = PIL.Image.open("mymap2.png")
#imageFile = "mymap2.png"
#Code from https://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint
#print(toopen)
u = urllib.urlopen(toopen)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
global imgtoprint
imgtoprint = Tkinter.PhotoImage(data=b64_data)
panel1 = Tkinter.Label(window, image=imgtoprint, bg='black')
panel1.pack(side='top', fill='both', expand='yes')
panel1.place(x=250, y=115)
b = Button(window, text="Browse for XML File", font=("Helvetica", 15), command=fileback, bg = 'black')
b.pack()
b.place(x=425,y=650)
c = Button(window, text="Toggle Orbit Prediction on Map", font=("Helvetica", 15), command=togglemap, bg = 'black')
c.pack()
c.place(x=425,y=850)
mapupdater()
window.mainloop()
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).