【问题标题】:Tkinter removing buttons gets error list index out of rangeTkinter 删除按钮使错误列表索引超出范围
【发布时间】:2020-07-19 16:37:21
【问题描述】:

我目前遇到的问题是,在从窗口中删除小部件时,我收到一条错误消息,提示列表索引超出范围并且没有删除所有小部件。我到处寻找答案,但没有发现任何有我的问题。

main.py:

#!/usr/bin/python3
from tkinter import *
from tkinter.ttk import *
import subprocess as sub
from sys import platform
import time
from threading import *
from pathlib import Path
import ugmfunctions

def rmvusrgrubutton(widget):
    #scrip = scriptrunnerGUI()
    #print(scrip.usrd)
    #scrip.usrd = 1
    #print(scrip.usrd)
    print(widget)
    print('Removing User / Group Settings buttons')
    #scrip.usrgru()
    widget.grid_remove()

def chngTOusr():
    scrip = scriptrunnerGUI()
    print(scrip.usrd)
    print(scrip.mmd)
    scrip.usrd = 0
    scrip.mmd = 1
    print(scrip.usrd)
    print(scrip.mmd)
    scrip.usrgru()

def rmvmmbuttons():
    scrip = scriptrunnerGUI()
    print(scrip.mmd)
    scrip.mmd = 1
    print(scrip.mmd)
    print('Removing main menu buttons...')
    scrip.mmenu()

def chngTOmm():
    scrip = scriptrunnerGUI()
    print(scrip.mmd)
    print(scrip.usrd)
    scrip.mmd = 0
    scrip.usrd = 1
    print(scrip.mmd)
    print(scrip.usrd)
    scrip.usrgru()


def doNothing():
    print('I do nothing')

class scriptrunnerGUI():
    ssh = ''
    ftp = ''
    proftpd = ''
    vsftpd = ''
    web = ''
    apaweb = ''
    nginweb = ''
    smb = ''
    sql = ''
    rsnc = ''
    buttons = []
    usrgrubuttons = []
    usrd = 0
    mmd = 0
    fconf = 0

    def __init__(self):
        self.mmenu()

    def mmenu(self):
        print('In Main Menu')
        self.header = Label(text='Main Menu')
        self.header.config(font=18, background='lightblue')
        self.header.grid(row=0)#, sticky='WE')

        buttonNames = ['Search For Prohibited Media', 'Updates', 'User / Group Settings', 'Firewall Settings', 'Services Settings', 'Malware Removal', 'Audit System', 'Basic Configurations', 'Remove Prohibited Software']


        #commands = [thred.threaderSRCH, thred.threaderUPDT, chngTOusr, thred.threaderFWL, thred.threaderServ, thred.threaderMALREM, thred.threaderALYN, thred.threaderBASEconf, thred.threaderRMproCont]
        # commands = [mmfunc.srchmedia, mmfunc.updates, self.usrgru]
        gridrow = ['5', '1', '1', '2', '2', '3', '4', '4', '3']
        gridcolumn = ['0', '0', '1', '0', '1', '1', '0', '1', '0']

        for i in range(0, 9):
            #try:
            #self.buttons.append(Button(root, text=buttonNames[i], width='40', command=lambda: Thread(target=self.commands[i]).start()))
            self.buttons.append(Button(text=buttonNames[i], width='40', command=self.usrgru))
            if self.mmd == 0:
                self.buttons[i].grid(row=gridrow[i], column=gridcolumn[i], pady='2', padx='5')
            else:
                self.buttons[i].grid_remove()

    def usrgru(self):
        buttonNames = ['Back to Main Menu', 'Add User to System', 'Remove User from System', 'Add Group to System', 'Remove Group from System', 'Add User to Group', 'Remove User from Group', 'List Local Users', 'List Local Groups', 'List Members of Group', 'List the Groups an User is in', 'Change all Users Passwords at Once']
        gridrow = ['7', '1', '1', '2', '2', '3', '3', '4', '4', '5', '5', '6']
        gridcolumn = ['0', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1', '0']
        self.header2 = Label(text='User and Group Settings')
        thredugm = ugmfunctions.ThreadUGMfunc()
        if self.usrd == 0:

            #print('usrd != 1')
            self.header2.grid(row=0, sticky='WE')
            self.header2.config(font=18, background='lightblue')
            print('In Users and Group Settings')
        else:
            # print('Destroying Header')
            rmvusrgrubutton(self.header2)
            #self.header2.grid_remove()

        for i in range(0, 12):
            if self.usrd == 0:
                self.usrgrubuttons.append(Button(text=buttonNames[i], width='40', command= lambda i=i: thredugm.threader(i)))
                #self.usrgrubuttons.append(Button(text=buttonNames[i], width='40', command=chngTOmm))
                self.usrgrubuttons[i].grid(row=gridrow[i], column=gridcolumn[i], pady='2', padx='5')
            else:
                print(self.usrgrubuttons[i])
                print('starting to delete buttons')
                rmvusrgrubutton(self.usrgrubuttons[i])
###################################################

if __name__ == '__main__':
    # creation of GUI
    root = Tk()
    root.title('Apple CIDR Script Runner')
    if platform == 'win32':
        root.geometry("565x300")
    elif platform == 'darwin':
        root.geometry("735x300")
    else:
        root.geometry("565x350")
    main = scriptrunnerGUI()
    root.mainloop()

####################################################

ugmfunctions.py:

#!/usr/bin/python3
import os
import subprocess as sub
from sys import platform
from threading import *
from tkinter import *
from tkinter.ttk import *
from removalTest import *


class usrGruFunc:
    def addusr():
        rootusr = Tk()
        if platform == 'debian' or platform == 'ubuntu' or platform == 'win32':
            useryon = ''
            userlbl = Label(rootusr, text='Would you like to add a user? [yes/no] ')
            userlbl.grid(row='1', column='1', sticky='W')
            usery = Button(rootusr, text='yes')
            usery.grid(row='2', column='1', sticky='W')
            usern = Button(rootusr, text='no')
            usern.grid(row='2', column='1', padx='80', sticky='W')

            command = """read -p 'Would you like to add a user? [y/n] : ' aduseryn
        if [ $aduseryn = 'y' ]; then
            aduser=1
            while [ $aduser = 1 ]; do
                read -p 'What would you like to name this new user? : ' name
                read -p 'Is this user an Admin? [y/n] : ' adminyn
                if [ $adminyn = 'y' ]; then
                    sudo adduser --force-badname $name
                    sudo usermod -a -G sudo $name       #adds user to sudo group
                    sudo usermod -a -G adm $name   #adds user to admin group
                    echo "User ${name} has been created and has been added to admin and sudo groups"
                    echo "User ${name} has been created and has been added to admin and sudo groups
                else
                    sudo useradd $name
                    echo "User ${name} has been added!"
                fi
                read -p 'Would you like to add another user? [y/n] : ' aga
                if [ $aga = 'n' ]; then
                    $aduser=0
                fi
            done
            sleep 1s
        else
            usr_gru
        fi"""

            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')
        rootusr.mainloop()

    def rmuser():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def adgru():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def rmgru():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def adusrtogru():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def rmusrfrogru():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def lslocausr():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def lslocagru():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def lsmemgru():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def lsgruusrin():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

    def chngusrspass():
        if platform == 'debian' or platform == 'ubuntu':
            print('This command is not complete yet')
        elif platform == 'win32':
            print('This command is not complete yet')
        elif platform == 'darwin':
            print('This command is not complete yet')
        else:
            print('This command does not yet support this OS')

targets = [chngTOmm, usrGruFunc.addusr, usrGruFunc.rmuser, usrGruFunc.adgru, usrGruFunc.rmgru, usrGruFunc.adusrtogru, usrGruFunc.rmusrfrogru, usrGruFunc.lslocausr, usrGruFunc.lslocagru, usrGruFunc.lsmemgru, usrGruFunc.lsgruusrin, usrGruFunc.chngusrspass]

class ThreadUGMfunc:
    def threader(self, com):
        try:
            print(targets[com])
            threader = Thread(target=targets[com])
            threader.start()
        except Exception as e:
            print(e)
            print('Could not start thread')

我已将其缩小到函数 usgru 下 scriptrunnerGUI 类的 main.py 中的位置,其中显示:

 for i in range(0, 12):
            if self.usrd == 0:
                self.usrgrubuttons.append(Button(text=buttonNames[i], width='40', command= lambda i=i: thredugm.threader(i)))
                #self.usrgrubuttons.append(Button(text=buttonNames[i], width='40', command=chngTOmm))
                self.usrgrubuttons[i].grid(row=gridrow[i], column=gridcolumn[i], pady='2', padx='5')
            else:
                print(self.usrgrubuttons[i])
                print('starting to delete buttons')
                rmvusrgrubutton(self.usrgrubuttons[i])

当命令 chngT​​Omm 处于活动状态的行时,代码按预期工作,但是当命令为 lambda i=i: thredugm.threader(i) 时,它会中断并且我得到“列表索引超出范围错误”

有人可以向我解释我做错了什么吗?我更喜欢使用 lambda 命令,因为它运行所有其他按钮的命令。

对这个问题的任何帮助都会很棒!

更新--------

这是我得到的错误输出:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/michael/Desktop/removalTest.py", line 47, in chngTOmm
    scrip.usrgru()
  File "/home/michael/Desktop/removalTest.py", line 119, in usrgru
    print(self.usrgrubuttons[i])
IndexError: list index out of range

【问题讨论】:

  • 你能显示所有的错误回溯吗?

标签: python-3.x user-interface button tkinter graphics


【解决方案1】:

而不是

for i in range(12):

for i in range(0, len(buttonNames)):

似乎编写代码的用户出于某种原因将 12 作为硬编码值,而不是循环遍历这些小部件,而不管其中是否有 12 个。

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多