简体   繁体   中英

Python for loop doesn't work as expected

I don't get any error messages, but the for loop doesn't produce the same result as the explicit statements. kp is an instance of a class and key0-9 are child elements of that class. Should what I'm trying to do actually work? If yes then maybe its something about how PyQt4 classes are constructed that is the problem.

This works:

def open_kp1(self, kp, le):
    self.inputStr = le.text()
    kp.key1.clicked.disconnect()
    kp.key2.clicked.disconnect()
    kp.key3.clicked.disconnect()
    kp.key4.clicked.disconnect()
    kp.key5.clicked.disconnect()
    kp.key6.clicked.disconnect()
    kp.key7.clicked.disconnect()
    kp.key8.clicked.disconnect()
    kp.key9.clicked.disconnect()
    kp.key0.clicked.disconnect()
    ... more code

This does not:

def open_kp1(self, kp, le):
    self.inputStr = le.text()
    key_list = (kp.key1, kp.key2, kp.key3, kp.key4, kp.key5, kp.key6, kp.key7,
            kp.key8, kp.key9, kp.key0)
    for key in key_list:
        key.clicked.disconnect()
    ... more code

What seems to be the problem is while you are invoking the disconnect() function in for loop, there could be some error with the list depending on the scope you are using it in or some constraint against running the function in a loop.

A good way to debug this will be to run this code to see where the code is actually giving an error as the first resort so that you can provide more input here for people to answer.

def open_kp1(self, kp, le):
    self.inputStr = le.text()
    key_list = (kp.key1, kp.key2, kp.key3, kp.key4, kp.key5, kp.key6, kp.key7,kp.key8, kp.key9, kp.key0)
    print(key_list) # print the list to verify the list is indeed intact
    for key in key_list:
        print(key) # verify if something indeed is the problem with individual key or if the code ever enters the for loop.
        key.clicked.disconnect()
    ... more code

What you need to verify is that the list is indeed storing the pointers as you intend to.

Also, on a side note it is a good practice to run your app in debug mode so that you get a verbose description in case something goes sideways and upload the trace here.

edit: spelling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM