I would suggest you first try substituting Destroy for Hide, and then check the docs for methods associated with widgets so you can think for yourself and make associations in the future. And mark the thread "Solved".
I would suggest you first try substituting Destroy for Hide, and then check the docs for methods associated with widgets so you can think for yourself and make associations in the future. And mark the thread "Solved".
You should first test that the button is active, as you may be trying to delete a button that doesn't exits. So, a dictionary to store the button makes sense as you can look it up before trying to delete.
import wx
class Test:
def __init__(self):
app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Test App")
panel = wx.Panel(frame)
vboxsizer = wx.BoxSizer(wx.VERTICAL)
self.grid = wx.GridSizer(rows=0, cols=3)
self.button_dict = {}
for j in range(5):
b = wx.Button(panel, label="Remove Button %d" % (j), id=j)
self.grid.Add(b)
b.Bind(wx.EVT_BUTTON, self.remove_button)
self.button_dict[j] = b
vboxsizer.Add(self.grid, 1, border=2, flag=wx.EXPAND|wx.ALL)
panel.SetSizer(vboxsizer)
frame.Show(True)
app.MainLoop()
def remove_button(self, e):
button_num = e.GetId()
print "ID =", button_num, type(button_num)
if button_num in self.button_dict:
self.button_dict[button_num].Hide()
if __name__ == "__main__":
t = Test()
This is a simple dictionary with 'iamge' pointing to 'i am ge'. Most of the online tutorials cover dictionaries.
Start with the second element and use index-1. Also, you should check for less than the first element as well as greater than the last element.
nums_list = [1,5,9,11,13,21,27,29,32]
for index in range(1, len(nums_list)):
if num > nums_list[index-1] and num < nums_list[index]:
## or
if nums_list[index-1] < num < nums_list[index]:
Only one for loop would be used because you want to access the same relative position in each string. Also, do not use "i" as a variable name as it looks too much like the number 1.
def cromo(a, b):
inc = 0
if len(a) != len(b):
print "both strings must be the same length"
return -1
for ctr in range(len(a)):
if a[ctr] != b[ctr]:
inc = inc + 1
print inc
return inc
A = "gtggcaacgtgc"
B = "gtagcagcgcgc"
print cromo(A, B)
Some print statements should clear up some things. And note that your __add__ function will yield an error but that is something to address after you get this part working.
class mylist:
def __init__(self,l):
self.data = l;
def __add__(self,l):
self.data = self.data + l
def __repr__(self):
return self.data
x = mylist([1,2,3])
print x
print x.data
#x = x + [4,5]
#print x
Sorry, the power has been out for the last 2 days. Try something along these lines. I use vertical and horizontal boxes. There may be another way, but this is explicit and works for me. You should also place each horizontal+vertical box(es) in a separate function to make it easier to see what is going where.
import wx
class TestFrame ( wx.Frame ):
def __init__ ( self ):
wx.Frame.__init__ ( self, None, -1, 'wxPython' )
self.panel = wx.Panel ( self, -1 )
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
datepic = wx.DatePickerCtrl(self.panel, -1, size=(110, -1), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
choice_list = [' '+str(num) for num in range(1001,1100)]
print choice_list[0]
self.ch = wx.Choice(self.panel, -1, size=(100, 25), choices=choice_list)
self.ch.SetSelection(0)
hbox1.Add(datepic, 0, wx.ALL, 5)
hbox1.Add(self.ch, 0, wx.ALL, 5)
vbox.Add(hbox1, 0, wx.ALIGN_LEFT | wx.ALL, 5)
self.panel.SetSizer(vbox)
app = wx.App()
TestFrame().Show()
app.MainLoop()
Effbot's example for reading a file into memory, which can then be written anywhere you like as long as the files are not huge.
import zipfile
file = zipfile.ZipFile("samples/sample.zip", "r")
for name in file.namelist():
data = file.read(name)
print name, len(data), repr(data[:10])
This stripped down version appears to work for me, but it is rewritten because it was too difficult to tell the i, l, and 1's apart, let alone what the variables with nonsense names are supposed to contain.
import wx
class TestFrame( wx.Frame ):
def __init__( self ):
wx.Frame.__init__ ( self, None, -1, 'wxPython' )
self.panel = wx.Panel ( self, -1 )
choice_list = [' '+str(num) for num in range(1001,1100)]
self.ch = wx.Choice(self, -1, size=(100, 25), choices=choice_list)
self.ch.SetSelection(0)
app = wx.App()
TestFrame().Show()
app.MainLoop()
To start you off, look for redundant statements, like all of the if/elif at the end of the program that basically do the same thing. They can be replaced by a simple dictionary of values.
## The following 3 lines can be deleted for this example
#u = 1
#optimism = int(0)
#while (u != 0):
factor_dict = {"1": [0.862, 0.873],
"2": [0.951,0.965],
"3": [0.989,1.01],
"4": [1.022,1.036],
"5": [1.073,1.0827]}
optimism = ""
while optimism not in factor_dict:
optimism = raw_input(\
"""\nOn a scale of 1-5..
How Optimistic Do You Feel About The Remaining Grades?
Enter 1 if you plan to slack off.
Enter 2 if you're feeling somewhat pessimistic
Enter 3 if you're neutral.
Enter 4 if you're feeling good about the remainder.
Enter 5 if your grades are only going UP UP and AWAY!
I feel: """)
if optimism in factor_dict:
factor = random.uniform(factor_dict[0], factor_dict[1])
forecast = calc*factor/100
forecast *= grade_remain
forecast += ab
raw_input("Hit Enter To View Your Forecast.")
print "Your FORECASTED Grade is: ",forecast,"%"
else:
print "Please enter a value between 1-5."
You can code the not found numbers in two ways:
message_tup = ("vodafone ", "o2 ", "meteor ")
found = False
for x in range(3):
if networkList[x] in prefix_list: ## x = 0 through 2
msg+= "\n %s\t" % (message_tup[x])
found = True
if not found:
print "none of these were found",
for x in range(3):
print prefix_list[x],
print
#
# or use a function
def find_prefix(networkList, prefix_list):
message_tup = ("vodafone ", "o2 ", "meteor ")
for x in range(3):
if networkList[x] in prefix_list:
msg+= "\n %s\t" % (message_tup[x])
return True
print "none of these were found",
for x in range(3):
print prefix_list[x],
print
return False
If you store the prefixes in a list:
prefix1=userInput1[:3]
prefix2=userInput2[:3]
prefix3=userInput3[:3]
##
## becomes
prefix_list = [prefix[:3] for prefix in userInput]
You can then clean up the if() statements:
if prefix1==networkList[0] or prefix2==networkList[0] or prefix3==networkList[0]:
msg+= "\n"+" vodafone ""\t"
#
# + the other if() statements becomes
message_tup = ("vodafone ", "o2 ", "meteor ")
for x in range(3):
if networkList[x] in prefix_list: ## x = 0 through 2
msg+= "\n %s\t" % (message_tup[x]) ## literal in tuple = same 0 through 2
This is the preferred way to do it as you can then easily modify the code with additions to the list instead of more if statements.
It would be something along these lines, see "Functions" here:
def CoM_positions(value_in):
if some_condition: ## or whatever
CoM_return = CoM(value_in)
print CoM_return, value_in
return CoM_return
return_value = find_positions(positions)
better_values= CoM_positions(return_value)
print better_values
There are two problems that I can see. It should be "root.mainloop" and there is no config statement for load menu so only the empty "menubar" is displayed. Also, note the inconsistent use of master and self.master. I did not test with any of the commented lines included. If they contain other problems that you can not solve, post back.
from Tkinter import *
class Application(Frame):
def __init__(self, master=None):
# Frame.__init__(self, master)
# self.master.rowconfigure(0, weight=1)
# self.master.columnconfigure(0, weight=1)
# self.master.title('Test Menu')
self.createMenu(master)
#self.createShell()
def createMenu(self, master):
# menubar = Menu(master)
loadmenu = Menu(master)
loadmenu.add_command(label='Load', command=self.load)
loadmenu.add_command(label='Save', command=self.save)
loadmenu.add_separator()
loadmenu.add_command(label='Quit', command=master.quit)
#master.grid()
master.config(menu=loadmenu)
def createShell(self):
frame = Frame(width=400, height=300)
frame.grid()
def load(self):
print "load called"
def save(self):
print "save called"
## this function is not being used by the code as it is now
def quit(self):
pass
root = Tk()
app = Application(master=root)
root.mainloop()
This appears to work for the given test data.
test_data = open("./tmp/GL581_54270_28321_28325.dat", "rb").read()
all_groups = test_data.split("BASELINE")
print len(all_groups)
fp_out = open("./tmp/test_output", "wb")
for group in all_groups[1:]: ## removes empty, first split occurance
sep = group.partition("\n")
fp_out.write("BASELINE %s\n" % (sep[0]))
for x in range(12):
sep = sep[2].partition("\n")
fp_out.write("%s\n" % (sep[0]))
fp_out.write("-" * 50)
fp_out.write("\n")
fp_out.write(sep[2])
fp_out.write("\n")
fp_out.write("*"*50)
fp_out.write("\n\n")
fp_out.close()
i made a start but i cant make it work with the colour nor adding size dimensions.
That is a little vague. Post one function with a description of what you want it to do. Also in getWidth() and getHeight() it will error out in Python 2.X if a non-digit is entered (what version of Python are you using?). You should catch errors or use raw_input and test the string using isdigit() before converting to an int. And both of these functions, getWidth and getHeight, are the same except for the literal printed. You can use one function and pass "width" or "height" to it. Finally, note the difference in the variable names here
def drawPatchOne(win, Colours, y):
#patch1.setFill(colour)
You don't need recursion for this. Are you sure you are not supposed to sort in reverse order, i.e. maximum value is first. You can think of recursion as a while loop, with a function calling itself instead of looping.
It appears the the backslash is being escaped by Python. Try repr(the_string) as output and see if it helps.
There is an example in the turtle graphics demo of the Python docs that come with Python.
You also should test for length before you draw cards:
def cards(self):
if len(self.cardList) > 5):
for a in random.sample(self.cardList, 6):
Hey, I've got an array full of random numbers
It depends on how many levels are in the array. Generally, you would flatten the array into a single level list, and operate on that. If you want to keep the original structure, then you have to test for the type. If it is an integer you can modify if. If it is a list, then you have to traverse the inner list. Recursion would probably be the best choice for doing that.
If you are using Python3.X, then input will return a string which is always greater than 100, print type(score) to see which class it belongs to.
It appears the the zero is being read as minutes and the one as the hour. I doubt any of the cron programmers allowed for someone entering "01" instead of just "1".
Post a link to a sample file that we can use for testing when/if you want to take this tread any further.
Start by using a turtle triangle for the tree, add a small rectangle for the tree stump, and then modify the triangle to look more tree like.
Since the text in the example posted appears to end with a newline, you should be able to test a reasonable length of characters, I'm using 30, for the newline and if not found, or 13 text records were found, you have the start of the binary data. An example of how you could do that follows. Another way is to test for "BASELINE" and group the data from the start of "BASELINE" to the next occurrence. You could then start at the end position of each group and slice 262144 bytes. The following appears easier to understand to me but it is personal choice. For more specific info you should include a link to part of an actual file with a 5-10 of these record groups.
file_read = """BASELINE NUM: 258\n
MJD: 54270\n
SECONDS: 28321\n
CONFIG INDEX: 0\n
SOURCE INDEX: 2\n
FREQ INDEX: 0\n
POLARISATION PAIR: RR\n
PULSAR BIN: 0\n
FLAGGED: 0\n
WEIGHTS WRITTEN: 0\n
U (METRES): -18954.5\n
V (METRES): 99486.5\n
W (METRES): 54117.25\n
<F1><AA><E8><U+0084>^]^NDeR.<U+0085><B2><D4>B<D8>m<8B><C1><B3><91><E2>A<AA>f)
<C1>A<91>Ad<DD> <C1>^L^^%AESC<91><U+037F>c<9E> A^F<BE>0]<8D>@H<F8>^M<C0>m<D8>]@@3<F7>^W@<FF>^Z<96>><B6><B0><E9>@g<AA><CE>?dl<86>?^\<ED><FE><BD><BF><82><88>@<E8>"""
def find_newline(test_this):
print "test_this =", test_this
for ctr, ch in enumerate(test_this):
## this should work but you may have to use "if ord(ch) == 10"
if ch == "\n":
return ctr
return -1
position = 0
new_position = 0
text_list = []
while new_position > -1:
new_position = find_newline(file_read[position:position+30])
print position, new_position
if new_position > -1:
text_list.append(file_read[position:position+new_position]) ## removes "\n"
## change the following +2 to +1 because "\n" is 2 bytes in the example
## but is a decimal …
Hundreds of records is not much in today's world so you can read each file into a dictionary and go from there. A simple example to associate the two files because I am too tired to do more today. You can omit some of the unnecessary records from the dictionary or use as is and filter before writing to the third file.
## simulate 2 files read into lists using readlines()
file_1 = ['SU' ,
'PD-98059 PD-98059 Tanimoto from SU = 0.129213',
'BML-265 BML-265 Tanimoto from SU = 0.163743',
'BML-257 BML-257 Tanimoto from SU = 0.156627',
'SU 4312 SU 4312 Tanimoto from SU = 1',
'AG-370 AG-370 Tanimoto from SU = 0.264286',
'AG-490 AG-490 Tanimoto from SU = 0.347826',
'PD-98060 PD-98059 Tanimoto from SU = 0.129213',
'BML-265 BML-265 Tanimoto from SU = 0.163743',
'BML-257 BML-257 Tanimoto from SU = 0.156627',
'SU 4312 SU 4312 Tanimoto from SU = 1',
'AG-370 AG-370 Tanimoto from SU = 0.264286',
'AG-490 AG-490 Tanimoto from SU = 0.347826',
'PD-98061 PD-98060 Tanimoto from SU = 0.129213',
'BML-265 BML-265 Tanimoto from SU = 0.163743',
'BML-257 BML-257 Tanimoto from SU = 0.156627',
'SU 4312 SU 4312 Tanimoto from SU = 1',
'AG-370 AG-370 Tanimoto from SU = 0.264286',
'AG-490 AG-490 Tanimoto from SU = 0.347826']
file_2 = ['GF',
'PD-98059 PD-98059 Tanimoto from GF = 0.118483',
'BML-265 BML-265 Tanimoto from GF = 0.164179',
'BML-257 BML-257 Tanimoto from GF = 0.213904',
'SU 4312 SU 4312 Tanimoto from GF = 0.436364',
'AG-370 AG-370 Tanimoto from GF = 0.284848',
'AG-490 AG-490 …
It depends somewhat on what widget you want to set, but generally you can use configure. This is something I have lying around from somewhere and added a configure to change the background and foreground of the button when the top button is pressed. Another example is here. You also want to become familiar with the class structure as it is much easier to pass variables around when coding a GUI. The example at the link posted shows how to use a class for this.
from Tkinter import *
def callback1() :
print "Callback #1"
option1.configure(bg = 'white', fg='green')
def callback2() :
print "Callback #2"
def callback3() :
print "Callback #3"
##===============================================================
top = Tk()
##--- always place in upper left corner ( +10+10 )
## size = 200x200 = minimum size so it's big enough to be seen
top.geometry("150x150+10+10" )
label1 = Label( top, text = "Test Menu" )
label1.pack()
label2 = Label( top, text = "" ) ## blank line = spacer
label2.pack()
option1 = Button(top, text='Option 1',
command=callback1, bg='blue', fg='white' )
option1.pack(fill=X, expand=1)
option2 = Button(top, text='Option 2',
command=callback2, bg='green', fg='white' )
option2.pack(fill=X, expand=1)
option3 = Button(top, text='Option 3 - No Exit',
command=callback3, bg='black', fg='white' )
option3.pack(fill=X, expand=1)
exit= Button(top, text='EXIT',
command=top.quit, bg='red', fg='white' )
exit.pack(fill=X, expand=1)
top.mainloop()
I'm sure I could but I'm not the one who's taking the class.
Adding a print statement should help. If you want to store more than one value, a list is usually the container of choice.
def gp(a1,r,n):
## can also be done with list comprehension
print [ a1 * (r ** x) for x in range(n)]
while n > 0:
n = n - 1 ## if 'n' was 1 it is now zero
an = a1 * (r ** n)
print n, "returning", an
return an
You would have to test for "(" and then traverse (or split) to the ")". The letters in between would be divided by 1000.
I'm not sure what you are asking, but see if this helps:
## last line under main()
print "points for one", point_one.x, point_one.y
print "points for two", point_two.x, point_two.y
#
# and add this additional function to Triangle and call it
def print_points(self):
print self.A.x, self.A.y
print self.B.x, self.B.y
print self.C.x, self.C.y
## also under main()
triangle_one.print_points()
A big part of the problem is lazy naming. How in the hell can you tell what "self.A.x" contains?
It looks like you have 13 lines of normal text, by which I mean that you could open it normally and read the first 13 lines normally, and count the bytes to skip. Then close the file, open as binary and skip the number of bytes that contained text, but it is not easy to tell from the example.
Works fine for me. Note that you only have to pass minutes allowed and minutes used to the function.
def calc_total(minutesAllowed, minutesUsed):
extra = 0
if minutesUsed <= minutesAllowed:
totalDue =74.99
minutesOver = 0
print "You were not over your minutes for the month."
else:
minutesOver = minutesUsed - minutesAllowed
extra = minutesOver * .20
totalDue = 74.99 + extra
print "You were over your minutes by ",minutesOver
return totalDue, minutesOver
print calc_total(100, 90)
print calc_total(100, 110)
"""
You were not over your minutes for the month.
(74.99, 0)
You were over your minutes by 10
(76.99, 10)
"""
And what do you think does/does not happen here
print minutesAllowed, minutesOver, minutesUsed, totalDue
calcTotal(minutesAllowed, minutesOver, minutesUsed, totalDue)
print minutesAllowed, minutesOver, minutesUsed, totalDue
# the last letter is b,d,g,l,m,n,p,r,s or t
if word[wordlength] in ['b','d','g','l','m','n','p','r','s','t']:
#and the second to last letter is not the same as the last letter.
if word[wordlength] != word[wordlength-1]:
#
# or (same thing as nested if() statements)
if (word[wordlength] in ['b','d','g','l','m','n','p','r','s','t']) and \
(word[wordlength] != word[wordlength-1]):
#
# also only the replace can be used here (but the whole idea is incorrect)
# because a new string is created, so replace can be one or many characters
if word[wordlength]=="y":
word=word.replace('y', 'ier') ## *****test this with the word yummy*****
# word=word +'er' ## slice off the last "y" instead and add "ier"
The short answer is to use withdraw or iconify but not all methods are available for all widgets. A simple example that creates a normal Tk window, and a second window with a canvas that is withdrawn when you click the "Continue" button, and is raised with the "deconify" button. This is a quickie and so is crude but illustrates this.
import Tkinter
class TestClass():
def __init__(self):
self.top = Tkinter.Tk()
self.top.title("Test")
self.top.geometry("200x150+500+5")
frame_1 = Tkinter.Toplevel()
frame_1.title("frame 1")
but_1 = Tkinter.Button(self.top, text='deiconify',
command=frame_1.deiconify)
but_1.pack(side="bottom", fill=Tkinter.X, expand=1)
but_2 = Tkinter.Button(self.top, text='Quit',
command=self.top.quit, bg='blue', fg='yellow')
but_2.pack(side="bottom", fill=Tkinter.X, expand=1)
can_1 = Tkinter.Canvas(frame_1)
can_1.pack()
can_1.create_rectangle(50,50,100,100, outline='white', fill='black')
cont = Tkinter.Button(frame_1, text='CONTINUE',
command=frame_1.withdraw, bg='red', fg='white' )
cont.pack(side="bottom", fill=Tkinter.X, expand=1)
self.top.mainloop()
##====================================================================
if __name__ == '__main__':
CT=TestClass()
If I can read the 166 lines of code correctly, what happens when "resting" == 1
info_dict["resting"] = info_dict["resting"] - 1
## it now equals zero, so the following would never execute
def slime_move_ready():
## also add a print statement to see if this is executing
print 'info_dict["resting"]', info_dict["resting"]
if info_dict["resting"] > 0:
health.after(100, slime_move)
Also, use a tuple or another dictionary to replace all of the if() statements.
if info_dict["slime_spot"] == 1:
data = "east","east"
if info_dict["slime_spot"] == 2:
data = "west","south"
if info_dict["slime_spot"] == 3:
data = "east","south"
## etc, etc.
## becomes
info_tuple = ( ("", ""), ("east","east"), ("west","south"), ("east","south"))
info_dict = {"slime_spot":2 } ## test it
num = info_dict["slime_spot"]
data = info_tuple[num] ## or info_tuple[info_dict["slime_spot"]]
print data
For the unknowing, this is another example of the "never-ending-questions-with-little-or-no-code" method to get other people to write the code for them. The method is to keep asking questions until someone is worn down enough to write the code for them, while they sit on the veranda in the shade. Let this thread die as it should.
You would call it this way (an intro to classes):
##Test the Lexicon program
print'This is a test program for the Lexicon file'
# an instance of the class
lex_instance = Lexicon()
# the class instance now exists so we can call it's members
source = lex_instance.OpenFile('word')
faces=rect64(acb64583d1eb84cb),2623af3d8cb8e040;rect64(58bf441388df9592),d85d127e5c45cdc2
It appears that you could split on the comma and then on the semi-colon since you want the last string in the pair. Then flatten the resulting list. Otherwise, parse each line and look for a start and stop copying character (which may be easier to understand and is a skill that is necessary in a lot of real world applications).
launcher.get_config() // this should get me the IPs and their respective shares
trial.randomtask(2)
It gets the ip's and then destroys the dictionary because you don't store the return. You would then pass the returned dictionary, or an individual ip with shares, to the randomtask function.
It should be easier if you use a dictionary pointing to a list of shares. This code assumes that you do not care about order of execution, otherwise you will have to order the dictionary keys and execute in that order.
def get_config():
ip_dict = {}
done = False
deny = 'n'
counter = 1
while not done:
print " Type n or N to exit "
ip = raw_input("Enter IP: ")
print "you entered ", ip
ip=ip.lower()
if ip == 'n':
done = True
flag = True
else:
ip_dict[ip] = []
flag = False
## indent while() loop to this level
## problems with tabs-you can set an IDE to convert to spaces
while not flag:
share = raw_input("Enter Shares : ")
if share.lower() == deny.lower():
flag = True
else:
ip_dict[ip].append(share)
for ip in ip_dict:
print ip
for share in ip_dict[ip]:
print " ", share
takes a list of real numbers as input
And how are the numbers input; from a file, or via the keyboard. Whichever it is, that is where you want to start. Read the input from a file or the keyboard into a list, and post that code for further help.
Some modifications to your code
1. Used a list for keywords instead of if() statements
2. Added an indicator that turns on when "description" is found and prints those records. Add whatever to want to process those records instead of the print statement under "if des".
infile = open("books.txt","r")
lines = infile.readlines()
infile.close()
keywords = ("title", "author", "publisher")
print '{'
print ' "books":'
print ' "["'
des = False
for ctr in range(0, len(lines)):
commas = lines[ctr].split('*')
## look in a tuple instead of testing each with an if() statement
if commas[0] in keywords:
print ' {"%s":"%s"' % (commas[0], commas[1])
## some other keyword = set "description" to False
des = False
elif commas[0] == "description":
print "-"*50
des = True
## assuming you want to print the "description" line also
if des:
print lines[ctr]
What GUI toolkit are you using and what type of object is "frame"?
The code works fine for me on Slackware Linux. What are you using for input, and what output do you get?
The limits of floating point numbers
http://www.lahey.com/float.htm
http://docs.python.org/tutorial/floatingpoint.html
Use decimal for more precision.
from decimal import Decimal as dec
# 0.1 + 0.1 + 0.1 - 0.3 = 0.0
x = dec("0.1")
y = dec("0.3")
print x + x + x - y
Since there is no code on how or how many items in self.play_hands were declared, and no error message or what happened versus what was expected to happen, there is no way to comment. Generally, you would use list comprehension.
self.player_hands=[["Testcard"] for x in range(self.num_of_players)]
Also, "i" l" and "O" are not good choices for single digit variable names as they can look like numbers.