Not Enough Values to Unpack in Python GUI Application - python

I am writing a GUI application in Python using Tkinter. The application displays weather data for any given location and period of time chosen by the user. There are options for the user to display weather data for one week and one month. I am trying to display that data in a table, but I am getting the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Kevin\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\Kevin\Documents\Python\Weather Data Application\WeatherData.py", line 109, in getdata
for i, high, low, precip, conditions in enumerate(list, start = 1):
ValueError: not enough values to unpack (expected 5, got 2)
The table is supposed to have 5 columns. I am not sure why I am getting this error, as I have all the items I want to display in the list that I define. The part of the code that my error is occurring in is shown below:
#Display Data
for i in range(0,len(value)):
#Display data for one day
maxtemp = tk.Label(text = weather['locations'][place]['values'][i]['maxt'])
mintemp = tk.Label(text = weather['locations'][place]['values'][i]['mint'])
precipitation = tk.Label(text = weather['locations'][place]['values'][i]['precip'])
condition = tk.Label(text = weather['locations'][place]['values'][i]['conditions'])
if (radiovalue.get() == 2 and len(value) == 7) or radiovalue.get() == 3:
root.withdraw()
def goBack():
root.deiconify()
data.withdraw()
#new window
data = tk.Tk()
tablelabel = tk.Label(data, text = "Weather Data").grid(row = 0, columnspan = 5)
cols = ('Date', 'High Temperature', 'Low Temperature', 'Precipitation', 'Conditions')
weatherBox = ttk.Treeview(data, columns = cols, show = 'headings')
back = tk.Button(data, text = "Go Back", command = goBack).grid(row = 1)
for col in cols:
weatherBox.heading(col, text = col)
weatherBox.grid(row = 1, column = 0, columnspan = 5)
list = [weather['locations'][place]['values'][i]['maxt'],weather['locations'][place]['values'][i]['mint'],
weather['locations'][place]['values'][i]['precip'],weather['locations'][place]['values'][i]['conditions']]
for i, high, low, precip, conditions in enumerate(list, start = 1):
weatherBox.insert(values = (i, high, low, precip, conditions))

Related

Receiving error: _tkinter.TclError: invalid command name ".!frame3.!treeview"

I am writing a simple program for a local business that will allow its users to easily keep track of their job service tickets. At one point, I had the program working with no errors. However, being that I am very new to programming and had typed a lot of messy code, I went back and decided to clean some of it up, as well as added better functionality. In doing so, I caused an error to occur, and I can't seem to fix it.
I have tried multiple ways to solve this issue, but all I have been able to determine is that if I remove a small block of code, it will essentially run as it should.
Here are the two definitions:
def gui_elements_remove(self, elements):
for element in elements:
element.destroy()
def Load(self):
self.gui_elements_remove(self.gui_elements)
var = self.FirstTree.focus()
treevar = self.FirstTree.item(var)
JobDF = pd.DataFrame(treevar, index = [0])
self.JobID = JobDF.iloc[0]['values']
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID))
SP = cursor1.fetchall()
df = pd.DataFrame(SP, columns = [
'ServiceTicketsID',
'JobID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
])
columns = [
'ServiceTicketsID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
]
LoadFrame = Frame(self.root)
LoadFrame.pack(fill = BOTH, expand = True, padx = 50)
scroll = Scrollbar(LoadFrame, orient = VERTICAL)
SecondTree = ttk.Treeview(LoadFrame, yscrollcommand = scroll.set, columns = columns)
SecondTree['show'] = 'headings'
SecondTree.heading('#1', text = 'ServiceTicketsID')
SecondTree.heading('#2', text = 'Ticket Number')
SecondTree.heading('#3', text = 'Reason for Visit')
SecondTree.heading('#4', text = 'Warranty/VPO')
SecondTree.heading('#5', text = 'Date Ticket Received')
SecondTree.heading('#6', text = 'Date of Service')
SecondTree.heading('#7', text = 'Service Person')
SecondTree.column('#1', width = 0, stretch = NO)
SecondTree.column('#2', width = 75, stretch = YES, anchor = "n")
SecondTree.column('#3', width = 75, stretch = YES, anchor = "n")
SecondTree.column('#4', width = 75, stretch = YES, anchor = "n")
SecondTree.column('#5', width = 100, stretch = YES, anchor = "n")
SecondTree.column('#6', width = 100, stretch = YES, anchor = "n")
SecondTree.column('#7', stretch = YES, anchor = "n")
scroll.config(command = SecondTree.yview)
scroll.pack(side = RIGHT, fill = Y)
SecondTree.pack(fill = BOTH, expand = TRUE)
Maintree = df [[
'ServiceTicketsID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
]]
Maintree_rows = Maintree.to_numpy().tolist()
for row in Maintree_rows:
SecondTree.insert("", 0, values = row)
for col in columns:
SecondTree.heading(col, text=col, command=lambda _col=col: \
self.Treeview_sort_column(SecondTree, _col, False))
b1 = Button(LoadFrame, text = "Add")
b2 = Button(LoadFrame, text = "Update")
b3 = Button(LoadFrame, text = "Cancel")
b1.configure(command = lambda: self.Load_Add())
b2.configure(command = lambda: self.Load_Update())
#b3.configure(command = lambda: self.Cancel_Button(LoadFile, self.MainWindow, self.root))
b1.pack(side = LEFT, padx = 5, pady = 50)
b2.pack(side = LEFT, padx = 5, pady = 50)
b3.pack(side = LEFT, padx = 5, pady = 50)
There is more code but what I've provided should be more than enough, hopefully. The first method is called to clear out the frame from the previous method being run. The remainder is supposed to take the user's selection from the previous TreeView. However, upon running this code, I am given the error
_tkinter.TclError: invalid command name ".!frame3.!treeview"
If I comment out this block of code:
var = self.FirstTree.focus()
treevar = self.FirstTree.item(var)
JobDF = pd.DataFrame(treevar, index = [0])
self.JobID = JobDF.iloc[0]['values']
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID))
SP = cursor1.fetchall()
df = pd.DataFrame(SP, columns = [
'ServiceTicketsID',
'JobID',
'Ticket Number',
'Reason for Visit',
'Warranty/VPO',
'Date Ticket Received',
'Date of Service',
'Service Person'
])
As well as the remaining code affiliated with it, the program runs correctly. The frame is cleared out and the new TreeView is brought in, as well as its headers.
As I said, I am brand new to programming and as such am new to using StackOverflow. With that said, I apologize if I've not provided enough information, posted incorrectly, etc. I also apologize in advance for any sloppiness you may find in the code lol.
I appreciate all input.
JobDF = pd.DataFrame(treevar, index = [0])
and
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID))
were the culprits.
It should have been
JobDF = pd.DataFrame(treevar) #removed the index argument
and
cursor1 = self.cursor.execute("SELECT * from 'Service Tickets' WHERE JobID = ?", (self.JobID,)) #added a comma (self.JobID,))

Tkinter field in blank for Python

I need your help to figure out how to make the following coding:
My idea is to get a message if fields name and quantity are in blank at the time I execute a function through a button. I printed what is the value if name and quantity are in blank and program says it is .!entry and .!entry2 respectively.
Unfortunately it doesn't work. What I am doing wrong?
if name == .!entry and quantity == .!entry2:
message = Label(root, text = 'Name and Quantity required' , fg = 'red')
message.grid(row = 4, column = 0, columnspan = 2, sticky = W + E)
return
As #JordyvanDongen pointed out in the comments you should use entry.get() to get the text inside the the entry object.
I suggest this for you code, assuming the entry objects are named name and quantity:
if not name.get() or not quantity.get():
message = Label(root, text = 'Both name and quantity are required', fg = 'red')
message.grid(row = 4, column = 0, columnspan = 2, sticky = W + E)
return None
I changed the conditional to or so that if either of the fields are blank it will be triggered but you may want to change it back to and depending on your purposes..

Python GUI EntryButtons

I'm making a small GUI application that deals with grades and whatnot and outputs the highest grades and etc.
Here's a part of the code:
root = Tk()
gradeList = []
def addGradeObject(name, percentage):
gradeList.append(Grade(name, percentage))
updateOutput()
print(gradeList)
def undoAdd():
try:
gradeList.pop(len(gradeList) - 1)
updateOutput()
print(gradeList)
except Exception:
pass
def updateOutput():
highestGrade.setText(highest_grade(gradeList))
lowestGrade.setText(lowest_grade(gradeList))
numFailed.setText(num_failed(gradeList))
addButton = Button(text = "Add Grade", command = lambda: addGradeObject (entryA.get(), entryB.get())).grid(row = 1, column = 4)
undoButton = Button(text = "Undo", command = undoAdd).grid(row = 2, column = 4)
entryA = Entry()
entryA.grid(row = 1, column = 1)
entryB = Entry()
entryB.grid(row = 1, column = 2)
highestGrade = Entry()
highestGrade.grid(row = 2, column = 1)
lowestGrade = Entry()
lowestGrade.grid(row = 3, column = 1)
numFailed = Entry()
numFailed.grid(row = 4, column = 1)
root.title("Grade Checker")
root.mainloop()
The problem is I'm getting this error:
AttributeError: 'Entry' object has no attribute 'setText'
I don't understand. When you create an Entry box, doesn't the object of class "Entry" have an attribute/method that allows you to set text to it? I really don't know why it's not working
Entry methods can be found here. As far as I can tell, there is no setText method. There is however an insert method that you could use to set the text (though you might wand to delete the current text first).
def set_text(entry, text):
entry.delete(0, tkinter.END)
entry.insert(0 text)
Alternatively, you can hook the entry up to a StringVar and use it's .set() and .get() methods. e.g. (from the linked docs above):
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()

TypeError: unorderable types: str() < int()

Need help with this error.
my code:
from tkinter import *
def shouldIEat():
if calories.get() < 1523 :
answer.set("Eat food as soon as possible")
elif calories.get() > 1828 :
answer.set("Stop eating")
else:
answer.set("You can eat something, but don't go over 1828")
window = Tk()
answer = StringVar()
calories = IntVar()
calories.set(0)
caloriesLabel = Label(window, text = "How many calories have you consumed?")
caloriesLabel.grid( row = 1)
calories = Entry(width = 10)
calories.grid (row = 1, column = 1)
eatButton = Button(window, text = "Should I eat?" , command=shouldIEat).grid( row = 2 , column = 1)
quitButton = Button(window, text = "Quit" , command=window.quit).grid( row = 2 , column = 2)
window.mainloop()
My error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "D:/My Documents/School/Scripting Lang/Project", line 8, in shouldIEat
if calories.get() < 1523 :
TypeError: unorderable types: str() < int()
Your code sets up calories as a Tkinter IntVar, but then it clobbers it by creating an Entry with the same name. You need to give the Entry a different name, and then attach the calories IntVar using the textvariable argument in the Entry constructor.
Also, you never created a widget to display the answer.
from tkinter import *
def shouldIEat():
if calories.get() < 1523 :
answer.set("Eat food as soon as possible")
elif calories.get() > 1828 :
answer.set("Stop eating")
else:
answer.set("You can eat something, but don't go over 1828")
window = Tk()
answer = StringVar()
calories = IntVar()
calories.set(0)
#answer.set('')
caloriesLabel = Label(window, text = "How many calories have you consumed?")
caloriesLabel.grid(row = 1, column = 0)
caloriesEntry = Entry(width = 10, textvariable=calories)
caloriesEntry.grid(row = 1, column = 1)
Button(window, text = "Should I eat?", command=shouldIEat).grid(row = 2, column = 1)
Button(window, text = "Quit" , command=window.quit).grid(row = 2, column = 2)
answerLabel = Label(window, textvariable=answer)
answerLabel.grid(row = 2, column = 0)
window.mainloop()
We don't really need to initialise answer, but it is neater to do so. And you could use it to display some simple instructions, if you want.
There's another minor problem with your code that I should mention.
eatButton = Button(window, text = "Should I eat?" , command=shouldIEat).grid( row = 2 , column = 1)
This creates a Button object and then calls its .grid() method. That's fine, but the .grid() method returns None, it does not return the Button object, so saving that return value to eatButton is pointless. You don't need to keep a reference to that button for this program, which is why I changed it to
Button(window, text = "Should I eat?", command=shouldIEat).grid(row = 2, column = 1)
in my version. But when you do need to keep a reference to the widget you should construct it on one line and then apply the .grid() (or .pack()) method on a separate line, like you did with caloriesLabel.
BTW, in Python, names of the form calories_label are preferred over caloriesLabel. See PEP-008 for further details.
As you can see in the TypeError, you are comparing a string with an integer.
Cast your string to an integer before doing your comparison.

How can I put frames inside frames using tkinter?

I'm making a baseball program based on the strategy games produced by Avalon Hills from the 70s & 80s, and the last part is a gui. I've made all the code to run the game command line, and I've got the code to select lineups with a gui. I envision a 3by1 grid with a scoreboard on the first row, a text box displaying the result, out, home run, double play, etc., and the last row is divided between the pitcher and batter cards on the left side, and a frame of buttons. The frame will flip between an offence and defence frame. So first the defence frame comes up with options like pitching change, change position, and play ball. Play ball changes the frame to the offence options, which will be pinch hit, pinch run, steal, and so on. But how can I put the buttons inside a frame, then combine the player cards and buttons in another frame, and then add that to the main frame?
The DFrame & OFrame classes are inner classes (hence the "elf", not "self"). I've got the dynamic switching between the 2 Frames. My problem is breaking the DFrame main loop, it only plays the top of the first, and the self.roadOuts never increments. Here's what I've got:
while self.innings < 8.5 or self.homeScore == self.roadScore:
self.roadOuts = 0
while self.roadOuts < 3:
self.dFrame.mainloop()
class DFrame(Frame):
def __init__(elf, parent):
Frame.__init__(elf)
elf._playButton = Button(elf, text = 'Play Ball',
command = parent.oMenu)
elf._playButton.grid(row = 0, column = 0)
elf._pitchingButton = Button(elf, text = 'Pitching Change',
command = parent.pitchingChange)
elf._pitchingButton.grid(row = 1, column = 0)
elf._positionButton = Button(elf, text = 'Defensive Substitution',
command = parent.positionChange)
elf._positionButton.grid(row = 0, column = 1)
elf._alignButton = Button(elf, text = 'Change Positions',
command = parent.positionSwap)
elf._alignButton.grid(row = 1, column = 1)
elf._doubleButton = Button(elf, text = 'Double Switch',
command = parent.doubleSwitch)
elf._doubleButton.grid(row = 2, column = 0)
elf._walkButton = Button(elf, text = 'Intentional Walk',
command = parent.intentionalWalk)
elf._walkButton.grid(row = 2, column = 1)
elf._depthButton = Button(elf, text = 'Change Infield Depth',
command = parent.infieldDepth)
elf._depthButton.grid(row = 3, column = 0)
class OFrame(Frame):
def __init__(elf, parent):
Frame.__init__(elf)
elf._playButton = Button(elf, text = 'Play Ball',
command = parent.atBat)
elf._playButton.grid(row = 0, column = 0)
elf._pinchHitButton = Button(elf, text = 'Pinch Hit',
command = parent.pinchHit)
elf._pinchHitButton.grid(row = 1, column = 0)
elf._prfButton = Button(elf, text = 'Pinch Run First',
command = parent.pinchRunFirst)
elf._prfButton.grid(row = 0, column = 1)
elf._prsButton = Button(elf, text = 'Pinch Run Second',
command = parent.pinchRunSecond)
elf._prsButton.grid(row = 1, column = 1)
elf._prtButton = Button(elf, text = 'Pinch Run Third',
command = parent.pinchRunThird)
elf._prtButton.grid(row = 2, column = 1)
elf._stealButton = Button(elf, text = 'Steal',
command = parent.steal)
elf._stealButton.grid(row = 2, column = 0)
elf._bunt4HitButton = Button(elf, text = 'Bunt for a hit',
command = parent.bunt4AHit)
elf._bunt4HitButton.grid(row = 3, column = 0)
elf._hitNRunButton = Button(elf, text = 'Hit And Run',
command = parent.hitAndRun)
elf._hitNRunButton.grid(row = 4, column = 0)
elf._sacButton = Button(elf, text = 'Sacrifice',
command = parent.sacrifice)
elf._sacButton.grid(row = 4, column = 1)
elf._squeezeButton = Button(elf, text = 'Squeeze',
command = parent.squeeze)
elf._squeezeButton.grid(row = 3, column = 1)
the next method is called when the DFrame "play ball" button is clicked, and it makes the OFrame.
def oMenu(self):
self.dFrame.grid_forget()
self.dFrame.destroy()
self.oFrame = self.OFrame(self)
self.oFrame.grid(row = 1, column = 1)
self.oFrame.mainloop()
and at the end of an at bat, I have:
self.oFrame.grid_forget()
self.oFrame.destroy()
self.dFrame = self.DFrame(self)
self.dFrame.grid(row = 1, column = 1)
I'm not sure I understand your question. It seems like you know how to put one frame in another (It is really not much different than adding a Button to a frame -- or any other widget). I think what you're asking is how to dynamically switch which frame is being displayed at any given time.
You probably want the grid_forget method. using the play_ball button should cause the defense_frame to call it's grid_forget method, while re-gridding the the offense_frame. Of course, this would be pack_forget if you're using the pack geometry manager.
EDIT
Added a very rudimentary working example of the grid layout you described. It can probably be done a lot better, but this should get you started. (Particularly the switchOffenseDefense function and the switch_button button).
import Tkinter as tk
base=tk.Tk() #this is the main frame
root=tk.Frame(base) #Really this is not necessary -- the other widgets could be attached to "base", but I've added it to demonstrate putting a frame in a frame.
root.grid(row=0,column=0)
scoreboard=tk.Frame(root)
scoreboard.grid(row=0,column=0,columnspan=2)
###
#Code to add stuff to scoreboard ...
# e.g.
###
scorestuff=tk.Label(scoreboard,text="Here is the scoreboard")
scorestuff.grid(row=0,column=0)
#End scoreboard
#Start cards.
cards=tk.Frame(root)
cards.grid(row=1,column=0)
###
# Code to add pitcher and batter cards
###
clabel=tk.Label(cards,text="Stuff to add cards here")
clabel.grid(row=0,column=0)
#end cards
#Offense/Defense frames....
offense=tk.Frame(root)
offense.grid(row=1,column=1)
offense.isgridded=True #Dynamically add "isgridded" attribute.
offense_label=tk.Label(offense,text="Offense is coolest")
offense_label.grid(row=0,column=0)
defense=tk.Frame(root)
defense.isgridded=False
defense_label=tk.Label(defense,text="Defense is coolest")
defense_label.grid(row=0,column=0)
def switchOffenseDefense():
print "Called"
if(offense.isgridded):
offense.isgridded=False
offense.grid_forget()
defense.isgridded=True
defense.grid(row=1,column=1)
else:
defense.isgridded=False
defense.grid_forget()
offense.isgridded=True
offense.grid(row=1,column=1)
switch_button=tk.Button(root,text="Switch",command=switchOffenseDefense)
switch_button.grid(row=2,column=1)
root.mainloop()

Categories

Resources