woooee 814 Nearly a Posting Maven

Instead of 84 lines of code, with no idea what the problem is, compose the program in steps and test after each step. To get you started: (note the difference between final three lines here, and your code).

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

import math
import cmath

class RootFinder():
    def __init__(self, master=None):
        self.fr = tk.Frame(master)
        self.fr.grid()
        self.create_widgets()

    def create_widgets(self):
        self.labelf=tk.Label(self.fr, text="What is f(x)?", font='Arial 10 bold', pady=5)
        self.labelf.grid(row=0, column=0, sticky='w')

        self.sqrcoeff=tk.Entry(self.fr, width=5)
        self.sqrcoeff.grid(row=1, column=0)
        self.sqrcoeff.insert(0, '1')

root = tk.Tk()
RF = RootFinder(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

Lol, I feel stupid now...

That's always the case __after__ you find the problem.

woooee 814 Nearly a Posting Maven

There are a lot of problems with the code you posted:

## there is no root window
app=RootFinder()
app.mainloop()
#----------  should be 
root = Tk()
app=RootFinder(root)
root.mainloop()
#
## self.outputframe is never declared in the code you posted
    def create_widgets(self):
        self.root1lbl=Label(self.outputframe, text='')

And that is all that I care to examine at this point. See Ene Uran's example for starters.

woooee 814 Nearly a Posting Maven

Match up the parens on the previous, raw_input, statement. Also, the welcome() function does nothing.

vegaseat commented: yes +15
woooee 814 Nearly a Posting Maven

I am guessing that the window doesn't contain anything visible, just containers. (This just displays a button.)

import sys
from PyQt4 import QtCore, QtGui
 
class UI_CMDTester:
    def __init__(self):
        self.__app = None
        self.__win = None
        
        
        
        
    def init(self,    \
             w_title, \
             w_width, \
             w_height):
        
        self.__app = QtGui.QApplication(sys.argv)
        self.__create_win(w_title, w_width, w_height)
        
        sys.exit(self.__app.exec_())
        
    def __create_win(self, w_title, w_width, w_height):
        
        self.__win = QtGui.QWidget()
        self.__win.resize(w_width, w_height)
        self.__win.setWindowTitle(w_title)
        
        close_button = QtGui.QPushButton("&Quit")

        layout = QtGui.QGridLayout()
        layout.addWidget(close_button, 1, 0)
        self.__win.setLayout(layout)

        self.__win.show()
        

if __name__ == "__main__":
    obj_ct = UI_CMDTester()
    obj_ct.init("Window", 800, 600)
woooee 814 Nearly a Posting Maven

This statement will never be true

while decimal == '1' and decimal == '0' :
# ---- and this statement is meaningless
number=number

And str(decimal) will replace the binaryConvert() function. Also, press the code button to include your code in a readable (properly indented) form.

woooee 814 Nearly a Posting Maven

The result is correct since you open it for reading before anything is written to it.

text = "aim low and reach it"

fname = "test7.txt"
 
with open(fname, 'w') as foutp:
    # write text to file
    foutp.write(text)

# read text from file
with open(fname, 'r') as finp:
    mytext = finp.read()
 
print("to file --> %s" % text)
print('-'*30)
print("from file --> %s" % mytext)
bumsfeld commented: clearer +11
woooee 814 Nearly a Posting Maven

What happens when radius is greater than x or y. I get something like
x, y, radius 0.492985971944 0.492985971944 13 --> -12.5070140281 -12.5070140281
(And note that we will not do your homework for you, so if this gobbledygook was thrown together with the hope that we would code it for you, you are going to be disappointed)

radius = random.randint(5, 20)
topL = graphics.Point(x-radius, y-radius)
import graphics
import random

def constructBoard():
    win=graphics.GraphWin("Tic Tac Toe",500,500)
    win.setCoords(0.0,0.0,3.0,3.0)
    line1=graphics.Line(graphics.Point(1,0), graphics.Point(1,3)).draw(win)
    line2=graphics.Line(graphics.Point(2,0), graphics.Point(2,3)).draw(win)
    line3=graphics.Line(graphics.Point(0,1), graphics.Point(3,1)).draw(win)
    line4=graphics.Line(graphics.Point(0,2), graphics.Point(3,2)).draw(win)
    return win

def player_common(win):
    mouseClick = win.getMouse()
    x=mouseClick.getX()
    y=mouseClick.getX()
    radius = random.randint(5, 20)
    print "x, y, radius", x, y, radius, "-->", x-radius, y-radius
    topL = graphics.Point(x-radius, y-radius)
    botR = graphics.Point(x+radius, y+radius)

#    return topL, botR

    ## test a return with a reasonable number 
    return x-0.01, y-0.03

def player1Move(win):
    topL, botR = player_common(win)

    ## there is no difference between the next two lines so you will get a
    ## point, not a line
    player1X = graphics.Line(graphics.Point(topL, topL), graphics.Point(botR, botR))
    player1X = graphics.Line(graphics.Point(topL, topL), graphics.Point(botR, botR))
    player1X.draw(win)
    
    
def player2Move(win):
    topL, botR = player_common(win)

    ## shouldn't there be a circle radius somewhere??
    player2Circle = graphics.Circle(topL, botR)
    player2Circle.draw(win)
    
if __name__ == "__main__":
    win = constructBoard()
    player1Win = False
    player2Win = False
    while player1Win == False and player2Win == False:
        player1Move(win)
        player2Move(win)
woooee 814 Nearly a Posting Maven

Thanks for stating the obvious. We sometimes get too caught up in problem solving and forget to mention good techniques. Data validation should be the first step.

woooee 814 Nearly a Posting Maven

]AttributeError: 'NoneType' object has no attribute 'getMouse'

"win" = constructBoard() = None as constructBoard doesn't return anything. Also, python naming conventions use lower case with underscores for function names, and there it is poor style to construct a separate "main" function, especially since it is never called.

woooee 814 Nearly a Posting Maven

If it is easier to understand, reduce the lists first and then create the dictionary.

list_1= ['0 ', '512 ', '1 ', '513 ', '2 ', '514 ', '3 ', '515 ', '4 ', '516 ', '5 ', '517 ', '6 ', '518 ', '7 ', '519 ', '8 ', '520 ', '9 ', '521 ', '10 ', '522 ', '11 ', '523 ', '12 ', '524 ', '13 ', '525 ', '14 ', '526 ', '15 ', '527 ', '16 ', '528 ', '17 ', '529 ', '168 ', '530 ', '169 ', '531 ', '170 ', '532 ', '171 ', '596 ', '172 ', '597 ', '173 ', '598 ', '174 ', '599 ', '175 ', '600 ', '176 ', '601 ', '177 ', '602 ', '178 ', '603 ', '179 ', '604 ', '180 ', '605 ', '181 ', '606 ', '182 ', '607 ', '183 ', '608 ', '184 ', '609 ', '185 ', '610 ']

list_2 = ['0', '344', '1', '345', '2', '346', '3', '347', '4', '348', '5', '349', '6', '350', '7', '351', '8', '352', '9', '353', '10', '354', '11', '355', '12', '356', '13', '357', '14', '358', '15', '359', '16', '360', '17', '361', '18', '512', '19', '513', '20', '514', '168', '515', '169', '516', '170', '517', '171', '518', '172', '519', '173', '520', '174', '521', '175', '522', '176', '523', '177', '524', '178', '525', '179', '526', '180', '527', '181', '528', '182', '529']

print [[list_1[y], list_2[y]] for y in range(1, len(list_1), 2)]
woooee 814 Nearly a Posting Maven

A proof that your concept is correct, so any problem must lay somewhere else. And you should not use "id" as a variable name as it is already used by Python.

import pickle

class User():
    id = 1
 
    def __init__(self):
        self.id = User.id
        User.id +=1

dict_of_classes = {}
for name in ["Bill", "Sally", "George"]:
    instance = User()
    print name, instance.id
    dict_of_classes[name] = instance

## second test
pickle.dump( dict_of_classes, open( "save.p", "wb" ) )
dict_read = pickle.load( open( "save.p" ) )

print
for key in dict_read:
    instance = dict_read[key]
    print key, instance.id

## add another user to the dictionary read from the file
instance = User()
print "Pete", instance.id
dict_read["Pete"] = instance
woooee 814 Nearly a Posting Maven

We can help you with problems with code that is posted to the forum, but any forum that becomes "FreeProgramming.com" would immediately be buried by the requests for free programming.

woooee 814 Nearly a Posting Maven

You would use a dictionary of lists, The dictionary key is the person's name or ID, pointing to a list that can contain multiple activities for that person.

woooee 814 Nearly a Posting Maven

This is a quick program to get you started with a little less pain, but note that the only symbol that actually does anything is the "+" key, and it possibly doesn't do things in the order you want, but is intended as a starter only.

from tkinter import *
from tkinter import ttk
from decimal import *
from functools import partial

class Calculator():
    def __init__(self, master):
        self.master = master
        self.num_entered = ""
        self.total = Decimal("0")

        self.entry_label()
        self.number_buttons()
        self.symbol_buttons()

    def add_it(self):
        self.total += Decimal(self.num_entered)
        self.total_SV.set('Total=' + str(self.total))

    def div_it(self):
        print "div_it called"

    def entry_label(self):
        ## Label to display the total so far
        self.total_SV = StringVar()
        total_lab = Label(root, textvariable=self.total_SV)
        total_lab.grid(column=0, row=0, columnspan=2, sticky=(W,E))
        self.total_SV.set("Total =")

        # Calculator TextField
        self.dfSV = StringVar()
        dsplyF = Entry(root, textvariable=self.dfSV)
        dsplyF['state'] = 'readonly'
        dsplyF['readonlybackground']='white'
        dsplyF['foreground']='purple'
        dsplyF.grid(column=2, row=0, columnspan=2, sticky=(W,E))
        self.dfSV.set("")


    def mul_it(self):
        print "mul_it called"

    def number_buttons(self):
        """ button zero through 9 with button location in a list
        """
        button_location = [ [0, 5], [0, 2], [1, 2], [2, 2], \
                                    [0, 3], [1, 3], [2, 3], \
                                    [0, 4], [1, 4], [2, 4] ] 
        cs = 3                  ## columnspan
        for num in range(0, 10):
            but = ttk.Button(root, text=str(num), \
                             command=partial(self.pressed, str(num)), width=7)
            col = button_location[num][0]     ## get location from the list
            r   = button_location[num][1]
            but.grid(column=col, row=r, columnspan=cs, sticky=(W,E))
            cs = 1

    def pressed(self, button_value):
        print "pressed", button_value

        ## a dictionary of symbol keys and the function to execute
        ## for each key
        functions_dict = {"+":'self.add_it()', "-":'self.sub_it()', \
                          "*":'self.mul_it()', "/":'self.div_it()', \
                          "=":'self.total_it()' }

        if …
woooee 814 Nearly a Posting Maven

I have no time right now, but the error message is correct, equBPressed() has no knowledge of num1 or num2 because they were not passed to the function. You should be using a class for this as it solves a lot of those problems with self.var which is visible to all functions in the class; self.X_O_dict in the following program for example, For now, take a look at how this program uses "partial" to pass the button number to a common function.

from Tkinter import *
from functools import partial

class TicTacToe:
   def __init__(self, top):
      self.top = top
      self.button_dic = {}     ## pointer to buttons and StringVar()
      self.X_O_dict = {"X":[], "O":[]}  ## list of "X" and "O" moves
      self.top.title('Buttons TicTacToe Test')
      self.top_frame = Frame(self.top, width =500, height=500)
      self.buttons()
      self.top_frame.grid(row=0, column=1)

      exit = Button(self.top_frame, text='Exit', \
             command=self.top.quit).grid(row=10,column=0, columnspan=5)

      self.player = True   ## True = "X", False = "O"

   ##-------------------------------------------------------------------         
   def buttons(self):
      """ create 9 buttons, a 3x3 grid
      """
      b_row=1
      b_col=0
      for j in range(1, 10):
         self.button_dic[j] = StringVar()
         self.button_dic[j].set(str(j))
         b = Button(self.top_frame, textvariable = self.button_dic[j], \
                    command=partial(self.cb_handler, j))
         b.grid(row=b_row, column=b_col)

         b_col += 1
         if b_col > 2:
            b_col = 0
            b_row += 1

   ##----------------------------------------------------------------
   def cb_handler( self, square_number ):
      if self.player:                       ## True = "X", False = "O"
         player = "X"
      else:
         player = "O"

      ##--- square not already occupied
      if square_number not in self.X_O_dict["X"] and \
         square_number not in self.X_O_dict["O"]:

         self.button_dic[square_number].set(player)
         self.X_O_dict[player].append(square_number)
         self.check_for_winner(self.X_O_dict[player])
         self.check_for_tie()
         self.player = not self.player
      else:
         print "Occupied, pick another"

   ##----------------------------------------------------------------
   def check_for_tie(self):
      if 9 …
woooee 814 Nearly a Posting Maven

It works for me on Slackware Linux as well. Are you behind a firewall?

VulcanDesign commented: Thanks for the help! +2
woooee 814 Nearly a Posting Maven

To illustrate that the function is correct:

from decimal import Decimal
def calculate(num1, num2, oper):
    if(oper=="+"):
        answ = Decimal(num1) + Decimal(num2)
        return answ
    return 0
        
ret_ans = 0
for x in range(1, 6):
    print "%d + %d =" % (ret_ans, x),
    ret_ans = calculate(ret_ans, x, "+")
    print ret_ans
woooee 814 Nearly a Posting Maven

It is probably one of these
u[0][k+1]
but to find it you will have to put everything on separate lines, usually above the error line so it prints before the message,

derivative = (u[0][k+1]*u[1][k+1] - u[0][k-1]*u[1][k-1])
# and then break it down further, i.e. the last part of the equation
derivative += u[0][k+1]
derivative -= 2*u[0][k]
derivative += u[0][k-1]

and then print 0, k, k+1, k-1, len(u[0]) if that is the line the error message is on. It doesn't matter if the correct result is returned from the above, you just want to find the error.

woooee 814 Nearly a Posting Maven

Generally speaking, a dictionary should be used instead of several if/elif/else statements. It is easier to read and understand, and easier to modify since entries can be added or deleted from the dictionary. You will probably use dictionaries quite often so try to become more familiar with the object over time.

vegaseat commented: agree +15
woooee 814 Nearly a Posting Maven

The pointer is positioned at the end of the file so nothing is read.

import tempfile
if __name__ == '__main__':
  test = tempfile.NamedTemporaryFile()
  test.write('asdfsadfsadfsadfasdfasdfsadfsdfsadfsadfs')
  test.seek(0)                      ## offset=0 --> beginning of file
  print "\n test read", test.read()
  print test.name
woooee 814 Nearly a Posting Maven

NICOSIA (Reuters) – A court in Cyprus jailed three men for up to 20 months Monday for snatching the remains of late Cypriot President Tassos Papadopoulos from his grave.

The court ruled one of the defendants had asked his brother to dig up the remains, hoping he could negotiate his own release from prison where he is serving two life sentences for murder.

woooee 814 Nearly a Posting Maven

pygame has collision detection. Google is your friend. Even it you can't find an answer for your specific object, you can see how it is done with other objects.

woooee 814 Nearly a Posting Maven

There are several ways to do this. First, you might want to use a menu, with a number input, instead of keying in "aluminium", etc. as they can be spelled differently (aluminum). Then use a dictionary or list of lists to chain the values to the raw material.

material_dict = {"concrete" : 0.000012,
                 "silver" : 0.000019,
                 "gold" : 0.000014 }     ## etc
# or
material_list = [ ["concrete", 0.000012], \
                  ["silver", 0.000019], \
                  ["gold", 0.000014] ]
woooee 814 Nearly a Posting Maven

whats the best way to just show a blank if no number is entered

If no number is entered, the length would be zero.

import easygui

def check_numbers(number_entered, ctr):
    #Set list for networks
    networks = [ ["083", "3 Ireland"], ["085", "Meteor"], \
             ["086", "02"], ["087", "Vodafone"] ]

    if len(number_entered):     # some data was entered
        net = number_entered[0:3]
        found = 0
        for el in networks:
            if net == el[0]:
                easygui.msgbox("%s \t Is on the %s network" % \
                              (number_entered, el[1]))
                found = 1
        if not found:
            easygui.msgbox("%s\tIs an invalid mobile network number" % \
                           (number_entered))

    else:                               ## box is empty
        easygui.msgbox("No number entered for box %s" % (ctr))

runprog = "yes"

#Set promts for multenterbox
promt = "Enter the mobile numbers"
title = "Moble number checker"

#Set lists for multenterbox fields
fields = ["First number", "Second number", "Third number"]
userInput = []

while runprog.lower() == "yes":

    #Get user inputs
    userInput = easygui.multenterbox(promt,title,fields)

    #Split user input list into variables
    for ctr in range(3):
        check_numbers(userInput[ctr], ctr+1)

    #Ask user if they want to run the program again
    runprog = ""
    while runprog.lower() not in ["yes", "no"]:
        runprog = easygui.enterbox( \
                  "Would you like to check more mobile numbers? yes/no")
woooee 814 Nearly a Posting Maven

wx has a CallAfter method. It will require some implementation of multiprocessing/threads however you do it since you want to do two things at once: 1) wait for a button press, 2) keep track of the time that has passed. This programs waits for 5 seconds, simulating waiting for a button press, and after 5 seconds exits.

import time
from multiprocessing import Process

class TestClass():

   def test_f(self, name):
      ctr = 0
      while True:
         ctr += 1
         print ctr, name
         time.sleep(0.5)

if __name__ == '__main__':
   CT=TestClass()
   p = Process(target=CT.test_f, args=('Simulation of MessageBox',))
   p.start()

   ## sleep for 5 seconds and terminate
   time.sleep(5.0)
   p.terminate()
   p.join()

   print "\n\ndestroy here"
vegaseat commented: nice example +15
woooee 814 Nearly a Posting Maven

From the docs http://docs.python.org/library/subprocess.html

Popen.wait()

Wait for child process to terminate. Set and return returncode attribute.

Warning

This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.

woooee 814 Nearly a Posting Maven

Try replacing root.destroy with root.quit. Possibly the root window is destroyed but Tkinter is still running.

woooee 814 Nearly a Posting Maven

The obvious response is to find "TYPE=" in the string, but that is so obvious that I must not understand exactly what you are asking.

woooee 814 Nearly a Posting Maven

Lists are passed by reference, so the tuple contains the memory address of the list, not the list itself, and that doesn't change. Both of these statements will fail

my_tuple = (1, 2, 3, [4, 5, 6])

new_list = [4, 5, 6]
my_tuple[3] = new_list     ## new memory address
my_tuple[1] = "a"
woooee 814 Nearly a Posting Maven

The program has to take as input a .csv file and manipulate it and plot it accordingly.

The Python wiki contains a section on plotting tools. Other than that your question is impossible to answer as we have no idea if it is a 2D or 3D, bar or graph, etc. At the very least you should include code to read the file into a data container, and a sample of the data you want to plot.

woooee 814 Nearly a Posting Maven

Using the datetime module is an easy way to subtract one time value from another IMHO.

import datetime

# subtract 10:02:59 from 12:01:02
difference = datetime.datetime(2011, 5, 11, 12, 1, 2) - \
             datetime.datetime(2011, 5, 11, 10, 2, 59)
print "the difference is %s" % (str(difference))

#
# also note that split(":") is a better way to split the input
# and you can also check for len == 3
time_input = "2:03:05"
print time_input, "-->", time_input.split(":")
vegaseat commented: agree +14
woooee 814 Nearly a Posting Maven

Although we don't know the format of the file, this is probably a never-ending loop as you are iterating over, and appending to, the same list.

for data in citynames:
    citynames.append(data[0])

Run this snippit as it limits the list to a length of 100, instead of an infinite loop.

x = [ 1, 2, 3 ]
for ctr, el in enumerate(x):
    if len(x) < 100:  
        x.append(el)
        print ctr
print x
woooee 814 Nearly a Posting Maven

"Heaven has no rage like love to hatred turned, nor hell a fury like a woman scorned."

I'd rather not be reminded of John Wayne Bobbit and his ex Lorena.

woooee 814 Nearly a Posting Maven

numglobals.frame_19.Show()

It appears that you haven't defined numglobals.frame_19. Check the variable name and also see if any of the others work. Note also that numglobals has not been passed to the function so the function may not be aware of it.

woooee 814 Nearly a Posting Maven

Note that this line will never be true because city_name is a string, i.e. "0" != 0.
if city_name==0:
Also you compare if xcoord==0: twice and don't check ycoord. You can combine all of the input into a loop and avoid the redundancy, and FYI you are writing to a text file so all fields will be stored as strings, i.e. there is no reason to input floats unless you want to check for valid input.

spamWriter = open('cities.csv', 'a')     ## 'a' = append additional recs if file exists

total=input("How many cities do you have? ")

x = 0
while x  < total:
    print
    output_list = []
    for lit in ["What is the name of your city?<'0' exits> ", \
                "What is the x coordinate?<'0' exits> ", \
                "What is the y coordinate?<'0' exits> " ]:
        response = raw_input(lit)
        if response == '0':
            break
        else:
            output_list.append(response)    
    x+=1

    ## write each record as it is entered
    spamWriter.write("%s, %s, %s\n" % \
               (output_list[0], output_list[1], output_list[2]))
   
raw_input("press enter to exit")
woooee 814 Nearly a Posting Maven

First, there are two types of variables in classes, attributes and instance variables. I think you want instance variables, so you can have more than one human for example, with separate values for each one.

class Human:
    def __init__(self):
        self.isplayer = False
        self.nhealth = 20.0

    def health_add_one(self):
        self.nhealth += 1

## 2 separate humans
instance_1 = Human()
instance_2 = Human()

instance_1.health_add_one()
print instance_1.nhealth
print instance_2.nhealth

Next, store each instance in a dictionary or list that you can pass around the program.

Ene Uran commented: agree with you +13
woooee 814 Nearly a Posting Maven

There is a list on the Python wiki.

woooee 814 Nearly a Posting Maven

You can just code a while() instead of the if() and while().

hours = 0
while int(hours) > 60 or int(hours) < 1:
    hours=raw_input('Hours worked:')
    #
    # the following is poor syle; use if statement instead
    #if hours == 'DONE':
        #break
    #else
    #
    if hours.upper() != 'DONE':
        hwage = 0
        while int(hwage) > 20 or int(hwage) < 5:
            hwage=raw_input('Enter hourly wage:')
#
#etc. for the rest of the input
woooee 814 Nearly a Posting Maven

If it's not a tie, this will return None if the first test fails.

for row in WAYS_TO_WIN:
    if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
        winner = board[row[0]]
        return winner
    
    if EMPTY not in board:
        return TIE

    return None
#
#----------------------------------------------------
if EMPTY not in board:     ## only test once
    return TIE

for row in WAYS_TO_WIN:
    if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
        winner = board[row[0]]
        return winner
    
return None
woooee 814 Nearly a Posting Maven

This is called "non-sense code" (not my word). It is more straight forward to use

if not reply.isdigit() :
        continue
    # Convert it to number
    number = int( reply )
#
#
    if reply.isdigit() :
        # rest of instructions
        # Convert it to number
        number = int( reply )

Also you have redundant loops that can be combined:

chr_val_sum = 0
for letter in word :
    print letter + ": %d" % ord( letter )
    chr_val_sum += ord( letter )
print "Sum of the charater values of the word, '%s': %d" % ( word, chr_val_sum )

Python naming conventions when you get some extra time.

woooee 814 Nearly a Posting Maven

Are you using Python 2.x or Python 3.X as one uses raw_input and the other uses input?

# int converts input to an integer so delete it
ed = int(input('Would you like to encrypt or decrypt a message? '))
#
if ed == 'encrypt' or 'Encrypt' or 'ENCRYPT':
# should be
if ed in ['encrypt', 'Encrypt',r 'ENCRYPT']:
# or even better
if ed.lower() == 'encrypt':
#
#
# also
message = list(message)
print("Encoded message:")
# message is already a list
for i in list(message):

Info on keyboard input http://greenteapress.com/thinkpython/html/book006.html#toc61

woooee 814 Nearly a Posting Maven

I try to remove the wx.GridSizer and replace it with another one.

The wxpython docs list Detach, Remove, and RemoveSizer for a Sizer widger (GridSizer is a subclass of Sizer). So it would be something like (sorry, 186 lines of code is more than I want to wade through, though someone else may do it)

sizer = self.mainPanel.GetSizer()
sizer.Detach(0)
#
# or
sub_sizer = wxGridSizer(vgap=10, hgap=10)
sizer.Remove(sub_sizer)

#
#     Not a good example, but it works
#
import wx
 
class Test:
  def __init__(self):
    app = wx.App(False)
    self.app = app
    frame = wx.Frame(None, wx.ID_ANY, "Test App")
    panel = wx.Panel(frame)
    vboxsizer = wx.BoxSizer(wx.VERTICAL)
    self.frame = frame
    self.panel = panel
 
    self.grid = wx.GridSizer(rows=0, cols=3)

    self.button_dict = {}
    x = 10
    y = 20
    for j in range(5):
        print j, x, y
        b = wx.Button(panel, label="Remove Button %d" % (j), id=j, pos=(x, y))
        self.grid.Add(b)
        b.Bind(wx.EVT_BUTTON, self.removeButton)
        self.button_dict[j] = b
        x += 50
        if j == 2:
            x = 10
            y = 30 

    exit = wx.Button(panel, -1, 'Exit', (10, 200))
    exit.Bind(wx.EVT_BUTTON,  self.exit_this)

    vboxsizer.Add(self.grid, 1, border=2, flag=wx.EXPAND|wx.ALL)
    panel.SetSizer(vboxsizer)
    frame.Show(True)
 
    app.MainLoop()
 
  def removeButton(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].Destroy()

  def exit_this(self, event):
        self.frame.Destroy()

if __name__ == "__main__":
  t = Test()
vegaseat commented: very helpful +14
woooee 814 Nearly a Posting Maven

Define the math first. The two circles are colliding if the distance between the centers is less than or equal to the (radius of circle one + the radius of circle two. Dry it out on paper first).

woooee 814 Nearly a Posting Maven

First, what SQL db are you using. Assuming SQLite, the following code works. Note that "Urgent Help" does not stimulate us since it usually means that you have waited until the last minute to do some homework. I am guessing that the problem is that you don't close the db in initialise() and then open it again in the function. You should only open the db once and pass the cursor and connection.

import sqlite3 as sqlite

def initialise():
    MyConnection = sqlite.connect ('rockitrally.db')
    MyCursor = MyConnection.cursor()
    MyCursor.execute('''CREATE TABLE Customers
                    (CustomerID INTEGER PRIMARY KEY,
                    Forename TEXT,
                    Surname TEXT,
                    DOB TEXT,
                    Address TEXT,
                    Phone TEXT,
                    Email TEXT)''')
    MyCursor.execute('''CREATE TABLE Cars
                    (CarID INTEGER PRIMARY KEY,
                    Make TEXT,
                    Model TEXT,
                    Miles INTEGER,
                    Price REAL,
                    Number_Rentals TEXT)''')
    MyCursor.execute('''CREATE TABLE Rentals
                    (RentalID INTEGER PRIMARY KEY,
                    CustomerID INTEGER,
                    CarID INTEGER,
                    Forename TEXT,
                    Surname TEXT,
                    Make TEXT,
                    Model TEXT,
                    Price REAL)''')

    return MyCursor, MyConnection

def add_cars(cur, con):
    input = raw_input                     ## for Python 2.X
    Make=input("Enter the car's make: ")
    Model=input("Enter the car's model: ")
    Miles=int(input("Enter the car's mileage: "))
    Price=float(input("Enter the car's rental price: "))
    Number_Rentals=input("Enter how many times the car has been rented: ")
    cur.execute("INSERT INTO Cars VALUES (NULL,?,?,?,?,?)",(Make,Model,Miles,Price,Number_Rentals))
    con.commit()

def print_all_cars(cur):
    cur.execute('SELECT * FROM Cars')
    for row in cur:
        print row

cur, con = initialise()
add_cars(cur, con)
print_all_cars(cur, con)
woooee 814 Nearly a Posting Maven

To start you off (untested):

def find_longest_word(trigger_sentence):
    """ 2. = find the longest word in the trigger sentence
    """

    ## container for the longest word or words
    longest_list = [0]

    ## assumes no punctuation
    for word in trigger_sentence.split():
        ## new word found so re-initialize the list
        if len(word) > longest_list[0]:
            longest_list = [len(word), word]
        elif len(word) == longest_list[0]:
            longest_list.append(word)

    ## element[0] = length, [1]+ = word or words
    return longest_list

If you find that you have to access this function more than once, then change the list to a dictionary, with key=word length pointing to a list of words, then if you want the next longest word, you have it without going through the sentence again.

def find_sentence(longest_word_list, list_of_sents):
    """3- Find all the sentences of the corpus that contain the word at step2
    """

    sentences_found = []
    for sentence in list_of_sentences:
        ## if we are looking for "the" we do not want "there", so split the sentence
        sentence_list = sentence.split()
        ## multiple longest words can be found in the same sentence
        found = False
        for word in longest_word_list[1:]:
            if (not found) and (word in sentence_list): 
                found = True
                sentences_found.append(sentence)
    return sentences_found
woooee 814 Nearly a Posting Maven

You can't mention drinking without some of W.C. Fields' sayings
"A woman drove me to drink and I didn't even have the decency to thank her."

"Always carry a flagon of whiskey in case of snakebite and furthermore always carry a small snake."

Not drinking related, but one of my favorites
"Ah, the patter of little feet around the house. There's nothing like having a midget for a butler."

woooee 814 Nearly a Posting Maven

There is a space between the "def" and the function name, so it is
def __init__(self):

woooee 814 Nearly a Posting Maven

You can try either PySerial or PyUSB.

woooee 814 Nearly a Posting Maven

You would have to read each record ("lines" is a word processing term and many types of files do not have lines) until you reach the first "{". Then store or print the records until the next "}". Then switch off an indicator. Note that you might want to count the number of "{"s and the number of "}"s to allow for multiple levels, and when they are equal set the indicator to False. To stop the file read would be something like this pseudo-code:

reading = True
while reading:
   fp.readline()
   if "}" is found or end_of_file:
       reading = False