Hi all,
I'm trying to write a GUI that will put up multiple widgets in
succession, all using the same class. Here's the class for the widget:
class TwoChoice:
def __init__(self, master):
frame = Frame(master)
frame.pack()
m = Label(root, text= maentry)
m.pack()
n = Label(root, text= fave)
n.pack()
self.button = Button(frame, text=home_team, command=
self.comm_1)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text=vis_team,
command=self.comm_2)
self.hi_there.pack(side=LEFT)
def comm_1(self):
print home_team
root.quit()
def comm_2(self):
print vis_team
root.quit()
I call it by
root = Tk()
gui= TwoChoice(root)
root.mainloop()
The problem is that when I call it again with new values for the variables, it prints both the old values and the new values. Then, the third time I call it it prints all three values, etc. How do I get it to only print the current values of the variables? I hope this is clear, what I mean is that the second widget will appear with 4 buttons instead of 2, and I don't want that to happen.
Thanks,
Greg
10 1803
Hey, Greg, I'll be able to get to this in a while. In the meanwhile, it would be very helpful if you would post back using [code] tags around your code. Thanks.
This sounds like some problem with the "scope" of the variables.
For example it don't see
home_team and vis_team
in your class, nor how you are "calling" with new values.
Go ahead and post all the code using [code] tags, and I'll help you straighten things out.
Your post should look something like the following. It should run or produce any error that you are getting. This way somebody (probably me) can copy it, run it, fix it and repost it. Thanks -
from Tkinter import *
-
home_team = "Mets"
-
vis_team = "STL"
-
class TwoChoice:
-
def __init__(self, master):
-
frame = Frame(master)
-
frame.pack()
-
m = Label(root, text= "whatever")
-
m.pack()
-
n = Label(root, text= "whoever")
-
n.pack()
-
self.button = Button(frame, text=home_team, command=
-
self.comm_1)
-
self.button.pack(side=LEFT)
-
self.hi_there = Button(frame, text=vis_team,
-
command=self.comm_2)
-
self.hi_there.pack(side=LEFT)
-
def comm_1(self):
-
print home_team
-
# root.quit()
-
def comm_2(self):
-
print vis_team
-
# root.quit()
-
# I call it by
-
root = Tk()
-
gui= TwoChoice(root)
-
root.mainloop()
-
You should be able to preview and edit your post 'til it look right. Instructions for using code tags can be found in gray background writing while you are creating you post, in the posting guidelines to your right while you are creating you post or in the sticky at the top of this forum.
Thanks for your replies and help. I'm away from home right now and don't have access to my computer, but tomorrow I will post it using the code tags as you mention.
Greg
Thanks for your replies and help. I'm away from home right now and don't have access to my computer, but tomorrow I will post it using the code tags as you mention.
Greg
Thanks for the update!
Here is my program: - import urllib2
-
import string
-
import os
-
# from greg import *
-
import re
-
import Tkinter
-
from Tkinter import *
-
-
maentry=''
-
fave=''
-
home_team=''
-
vis_team=''
-
k=0
-
-
# This function reads line number lineno in a file
-
def readline(lineno, filename):
-
file=open(filename, "r")
-
y=1
-
while y<lineno:
-
file.readline()
-
y=y+1
-
content=file.readline()
-
return content
-
-
# This function counts the number of lines in a file
-
def countlines(filename):
-
file=open(filename, "r")
-
y=0
-
while 1:
-
if not file.readline(): break
-
y=y+1
-
return y
-
-
# Creates a widget with two choices on buttons.
-
class TwoChoice:
-
def __init__(self, master):
-
-
frame = Frame(master)
-
frame.pack()
-
m = Label(root, text= maentry)
-
m.pack()
-
n = Label(root, text= fave)
-
n.pack()
-
self.button = Button(frame, text=home_team, command= self.comm_1)
-
self.button.pack(side=LEFT)
-
-
self.hi_there = Button(frame, text=vis_team, command=self.comm_2)
-
self.hi_there.pack(side=LEFT)
-
-
def comm_1(self):
-
print home_team
-
root.quit()
-
-
def comm_2(self):
-
print vis_team
-
root.quit()
-
-
-
-
# The following is a function that gets the spread from a line containing it.
-
# It features some pretty damn inelegant code, but is simple and
-
# works.
-
def get_spread(line):
-
a = ''
-
w=1
-
while w<10:
-
if line[w]== '-':
-
a = line[w+1]
-
if line[w+2] == '<': break
-
else: a = a + line[w+2]
-
if line[w+3] == '<': break
-
else: a = a + line[w+3]
-
if line[w+4] == '<': break
-
else: a = a + line[w+4]
-
w+=1
-
return a
-
-
# This function looks at the file for any team from the list, then looks two
-
# lines further for its opponent. Then switches home and away if necessary.
-
# Then writes the matchup to a file. The global line allows the function
-
# to change variables globally. The break lines are necessary, and probably
-
# just a good idea in general, b/c once you find a team that matches you
-
# don't want to look for any more, or things can get screwed up.
-
def findteams():
-
global y, k, home_team, vis_team, fave, maentry
-
line = readline(y, 'temp.txt')
-
for team in teams:
-
if string.find(line,team) >= 0:
-
home_team = team
-
y+=1
-
line = readline(y, 'temp.txt')
-
spread= get_spread(line)
-
fave = home_team + ' favored by ' + spread+ '\n'
-
y+=1
-
line = readline(y, 'temp.txt')
-
for team2 in teams:
-
if string.find(line,team2) >= 0:
-
vis_team = team2
-
break
-
if string.find(line, 'At') >= 0:
-
home_team, vis_team = vis_team, home_team
-
maentry=teams[vis_team]+" at "+teams[home_team]+'\n'
-
#email = open('maemail.txt','a')
-
#email.write(maentry + fave)
-
k=1
-
break
-
-
teams = {'Baltimore': 'Baltimore Ravens', 'Buffalo': 'Buffalo Bills',
-
'Cincinnati': 'Cincinnati Bengals', 'Cleveland': 'Cleveland Browns',
-
'Denver': 'Denver Broncos', 'Houston': 'Houston Texans',
-
'Indianapolis': 'Indianapolis Colts', 'Jacksonville': 'Jacksonville Jaguars',
-
'Kansas City': 'Kansas City Chiefs', 'Miami': 'Miami Dolphins',
-
'New England': 'New England Patriots','Jets': 'New York Jets',
-
'Oakland': 'Oakland Raiders','Pittsburgh': 'Pittsburgh Steelers',
-
'San Diego': 'San Diego Chargers','Tennessee': 'Tennessee Titans',
-
'Arizona': 'Arizona Cardinals','Atlanta': 'Atlanta Falcons',
-
'Carolina': 'Carolina Panthers', 'Chicago': 'Chicago Bears',
-
'Dallas': 'Dallas Cowboys', 'Detroit': 'Detroit Lions',
-
'Green Bay': 'Green Bay Packers','Minnesota': 'Minnesota Vikings',
-
'New Orleans': 'New Orleans Saints', 'Giants': 'New York Giants',
-
'Philadelphia': 'Philadelphia Eagles', 'St. Louis': 'St. Louis Rams',
-
'San Francisco': 'San Francisco 49ers', 'Seattle': 'Seattle Seahawks',
-
'Tampa Bay': 'Tampa Bay Buccaneers', 'Washington': 'Washington Redskins'}
-
-
-
# The following opens a webpage and saves the source as temp.txt
-
page = urllib2.urlopen('http://www.footballlocks.com/nfl_point_spreads.shtml').read()
-
-
-
tpage = open('temp.txt','w')
-
tpage.write(page)
-
tpage.close()
-
-
M= countlines('temp.txt')
-
-
#email = open('maemail.txt','w')
-
-
root = Tk()
-
-
y=1
-
while y <= M:
-
findteams()
-
if k==1:
-
gui= TwoChoice(root)
-
root.mainloop()
-
y += 1
-
k=0
-
-
-
# The following sends an email to me with all the info.
-
-
#SENDMAIL = "/usr/sbin/sendmail" # sendmail location
-
#p = os.popen("%s -t" % SENDMAIL, "w")
-
#p.write("To: g@nospam.com\n")
-
##p.write("From: g@spam.com\n")
-
#p.write("Subject: NFL picks\n")
-
#p.write("\n") # blank line separating headers from body
-
-
#p.write("Here are the football games for the week.\n")
-
-
#p.write("\n")
-
-
#text = open('maemail.txt','r')
-
-
#for line in text:
-
# p.write(line+"\n")
-
-
#p.close()
-
-
# Clean up. This runs the bash command rm.
-
#os.system('rm maemail.txt temp.txt')
-
What this program is supposed to do is go to a website and find all the football games for the week, as well as the spreads, and then put each game up one at a time on a Tkinter widget and ask me which one I think will win. I click on who I think, and then it sends me an email with my picks. The email part at the end I haven't finished, but that I know how to do. I think you will see the problem if you try to run it, the way each widget is just added to the one before.
I'm grateful for the help I'm getting. If you want to give any other advice on any other aspects of the program I'd be happy to hear it, b/c I'm trying to learn to program on my own and don't have a ton of experience.
This is a good one. I'll work on it a bit and get back to you.
This is a good one. I'll work on it a bit and get back to you.
Here is something to sink your teeth into. It works, but is not well tested.
It is (I feel) well structured so that you should be able to fix it easily.
I tried to keep it as much like the original as posible, but renamed a couple of variables. Regarding TKinter: pack() is the least used of the geometry managers. If you don't have a good Tkinter book, I can point you to some early docs that I learned from. -
-
import urllib2
-
import string
-
import os
-
# from greg import *
-
import re
-
import Tkinter
-
from Tkinter import *
-
# Global variables limit your ability to reuse your work
-
# so they are discouraged. Let's see if we can get them
-
# into your class
-
maentry=''
-
fave=''
-
home_team=''
-
vis_team=''
-
k=0
-
# This is OK, but may move to fuction for better separation of data and code.
-
teams = {'Baltimore': 'Baltimore Ravens', 'Buffalo': 'Buffalo Bills',
-
'Cincinnati': 'Cincinnati Bengals', 'Cleveland': 'Cleveland Browns',
-
'Denver': 'Denver Broncos', 'Houston': 'Houston Texans',
-
'Indianapolis': 'Indianapolis Colts', 'Jacksonville': 'Jacksonville Jaguars',
-
'Kansas City': 'Kansas City Chiefs', 'Miami': 'Miami Dolphins',
-
'New England': 'New England Patriots','Jets': 'New York Jets',
-
'Oakland': 'Oakland Raiders','Pittsburgh': 'Pittsburgh Steelers',
-
'San Diego': 'San Diego Chargers','Tennessee': 'Tennessee Titans',
-
'Arizona': 'Arizona Cardinals','Atlanta': 'Atlanta Falcons',
-
'Carolina': 'Carolina Panthers', 'Chicago': 'Chicago Bears',
-
'Dallas': 'Dallas Cowboys', 'Detroit': 'Detroit Lions',
-
'Green Bay': 'Green Bay Packers','Minnesota': 'Minnesota Vikings',
-
'New Orleans': 'New Orleans Saints', 'Giants': 'New York Giants',
-
'Philadelphia': 'Philadelphia Eagles', 'St. Louis': 'St. Louis Rams',
-
'San Francisco': 'San Francisco 49ers', 'Seattle': 'Seattle Seahawks',
-
'Tampa Bay': 'Tampa Bay Buccaneers', 'Washington': 'Washington Redskins'}
-
# Module scope "helper functions" are an OK practice (you'll see this often)
-
# This function reads line number lineno in a file
-
# "file" is a key word in python; better to use tmpFile or something
-
# files left open are handled by garbage collection, but better to tmpFile.close()
-
# Keep all the lines in a list for faster operation anyway
-
def readline(lineno, filename):
-
file=open(filename, "r")
-
y=1
-
while y<lineno:
-
file.readline()
-
y=y+1
-
content=file.readline()
-
return content
-
# This function counts the number of lines in a file
-
def countlines(filename):
-
file=open(filename, "r")
-
y=0
-
while 1:
-
if not file.readline(): break
-
y=y+1
-
return y
-
-
# Everything that a frame knows how to do should be a
-
# method of the frame. To promote reusability, subclass Frame
-
# Creates a widget with two choices on buttons. Handle all button clicks.
-
# store results. Application can ask how many results we've got and act on that.
-
# For now, we'll just quit the app at the end of the file.
-
# The current choices will be reflected on the widgets (not new widgets).
-
class TwoChoice(Frame): # This way a larger app can just pack this class.
-
def __init__(self, master):
-
Frame.__init__(self, master)
-
self.master = master
-
self.pickList = [] # Store picks here
-
self.lineNum = 1 # By moving "globals" here, you make this reusable
-
self.lineList = self.GetPageAsList() # Use descriptive variable names
-
self.nLines = len(self.lineList) # len() is really fast because objects
-
# know what their size is
-
home_team, vis_team, spread = self.FindTeams()
-
self.CreateWidgets(home_team, vis_team, spread) # This actually simplifies things
-
def CreateWidgets(self, home_team, vis_team, spread):
-
# Widgets make good storage for current values
-
maentry, fave = self.ConcatLabels(home_team, vis_team, spread)
-
self.gameLabel = m = Label(root, text=maentry)
-
m.pack()
-
self.oddsLabel = n = Label(root, text=fave)
-
n.pack()
-
self.homeButton = Button(self, text=home_team, command=self.OnHomeButton)
-
self.homeButton.pack(side=LEFT)
-
self.visButton = Button(self, text=vis_team, command=self.OnVisButton)
-
self.visButton.pack(side=LEFT)
-
def ChangeWidgets(self):
-
home_team, vis_team, spread = self.FindTeams()
-
maentry, fave = self.ConcatLabels(home_team, vis_team, spread)
-
self.homeButton.config(text=home_team)
-
self.visButton.config(text=vis_team)
-
self.gameLabel.config(text=maentry)
-
self.oddsLabel.config(text=fave)
-
-
def ConcatLabels(self, home_team, vis_team, spread):
-
maentry = teams[vis_team]+" at "+teams[home_team]+'\n'
-
fave = home_team + ' favored by ' + spread+ '\n'
-
return maentry, fave
-
def OnHomeButton(self):
-
teamName = self.homeButton['text']
-
self.pickList.append(teamName)
-
print teamName
-
self.ChangeWidgets()
-
# root.quit()
-
def OnVisButton(self):
-
teamName = self.visButton['text']
-
self.pickList.append(teamName)
-
print teamName
-
self.ChangeWidgets()
-
# root.quit()
-
-
# The following is a function that gets the spread from a line containing it.
-
# It features some pretty damn inelegant code, but is simple and
-
# works. [ could use line.find('-') instead of loop ]
-
def get_spread(self, line):
-
a = ''
-
w=1
-
while w<10:
-
if line[w]== '-':
-
a = line[w+1]
-
if line[w+2] == '<': break
-
else: a = a + line[w+2]
-
if line[w+3] == '<': break
-
else: a = a + line[w+3]
-
if line[w+4] == '<': break
-
else: a = a + line[w+4]
-
w+=1
-
return a
-
# This function looks at the file for any team from the list, then looks two
-
# lines further for its opponent. Then switches home and away if necessary.
-
# Then writes the matchup to a file. The global line allows the function
-
# to change variables globally. The break lines are necessary, and probably
-
# just a good idea in general, b/c once you find a team that matches you
-
# don't want to look for any more, or things can get screwed up.
-
def FindTeams(self):
-
found = 0
-
y = self.lineNum
-
while (y < self.nLines) and not found:
-
line = self.lineList[y]
-
for team in teams:
-
if string.find(line, team) >= 0:
-
found = 1
-
home_team = team
-
y += 1
-
line = self.lineList[y]
-
spread = self.get_spread(line)
-
y += 1
-
line = self.lineList[y]
-
for team2 in teams:
-
if string.find(line, team2) >= 0:
-
vis_team = team2
-
break
-
if string.find(line, 'At') >= 0:
-
home_team, vis_team = vis_team, home_team
-
break
-
y += 1
-
self.lineNum = y
-
return home_team, vis_team, spread
-
-
def GetPageAsList(self):
-
# Maybe make another Frame to pick the site if errors occure
-
# Since the description fits in a sentance, the code fits in a fuction (at least):
-
# The following opens a webpage and saves the source as temp.txt
-
page = urllib2.urlopen('http://www.footballlocks.com/nfl_point_spreads.shtml').read()
-
# Python has a tempfile object which creates its own temporary name + other handy stuff
-
# Another way to make a block of text into an iterable is page.split('\n')
-
# Test to see which is faster
-
# Maybe strip off unused lines to speed things up a bit
-
tpage = open('temp.txt','w')
-
tpage.write(page)
-
tpage.close()
-
tpage = open('temp.txt')
-
lineList = tpage.readlines()
-
tpage.close()
-
return lineList
-
def SendEmail(self):
-
pass
-
#email = open('maemail.txt','w')
-
-
if __name__ == "__main__": # This allows a bigger app to import this module
-
root = Tk()
-
mainFrame = TwoChoice(root)
-
mainFrame.pack()
-
root.mainloop()
-
##M= countlines('temp.txt')
-
##This all gets handled by button event handlers
-
##y=1
-
##while y <= M:
-
## findteams()
-
## if k==1:
-
## gui= TwoChoice(root)
-
## root.mainloop()
-
## y += 1
-
## k=0
-
-
# The following sends an email to me with all the info.
-
#SENDMAIL = "/usr/sbin/sendmail" # sendmail location
-
#p = os.popen("%s -t" % SENDMAIL, "w")
-
#p.write("To: g@nospam.com\n")
-
##p.write("From: g@spam.com\n")
-
#p.write("Subject: NFL picks\n")
-
#p.write("\n") # blank line separating headers from body
-
#p.write("Here are the football games for the week.\n")
-
#p.write("\n")
-
#text = open('maemail.txt','r')
-
#for line in text:
-
# p.write(line+"\n")
-
#p.close()
-
# Clean up. This runs the bash command rm.
-
#os.system('rm maemail.txt temp.txt')
-
-
Wow! Thanks for all of this. I tested it and it works, and is clearly much better than what I had. I don't understand it all, but hopefully will soon with a bit of work. Thanks a million, I can tell that this will be very valuable forn me to learn from.
Wow! Thanks for all of this. I tested it and it works, and is clearly much better than what I had. I don't understand it all, but hopefully will soon with a bit of work. Thanks a million, I can tell that this will be very valuable forn me to learn from.
You are very welcome! That's what we are here for. Keep posting,
Barton
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Matthew Wilson |
last post by:
Hi-
I've been goofing off with some basic recursive landscape generating
stuff, drawing the output to a tk window. You can run the program like
so:
from pts import *
>>> draw(5) #will...
|
by: Stewart Midwinter |
last post by:
I would like to link the contents of three OptionMenu lists. When I select an
item from the first list (call it continents), the contents of the 2nd list
(call it countries) would update. And in...
|
by: SeeBelow |
last post by:
Do many people think that wxPython should replace Tkinter? Is this
likely to happen?
I ask because I have just started learning Tkinter, and I wonder if I
should abandon it in favor of...
|
by: Harlin Seritt |
last post by:
I was looking at the Tcl/Tk sourceforge page and found that there were
a couple of new widgets being produced for Tcl 8.5. Does anyone know if
there are any Tkinter wrappers somewhere?
thanks,
...
|
by: Kevin F |
last post by:
I've been trying to implement this script, it polls an IMAP inbox for
unread messages and displays the sender and subject in a scrollable
window using Tkinter. However, when I try to change the...
|
by: Kevin F |
last post by:
Sorry to repost... but 4am didn't get much responses.
I've been trying to implement this script, it polls an IMAP inbox for
unread messages and displays the sender and subject in a scrollable...
|
by: www.web20developers.com |
last post by:
http://www.web20developers.com
http://www.web20developers.com/index.php?option=com_content&task=view...
Ajallerix : AJAX, simple, fast Web image gallery demo ; at Novell
AJAX -...
|
by: xqxq |
last post by:
First of all, I have to say that I'm rather newbie to Python, and I've got a problem with Tkinter. I'm writing a game (exactly photonic attack), and i want to have a simulation of a game computer vs...
|
by: Chris M. Thomasson |
last post by:
Here is the initial crude implmentation which compiles under Comeau with no
warnings:
___________________________________________________________________
#include <cassert>
#include <cstdlib>...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
| |