Проблема, с которой я сейчас сталкиваюсь, заключается в том, что при удалении виджетов из окна я получаю сообщение об ошибке, указывающее, что индекс списка выходит за пределы диапазона, и не удаляет все виджеты. Я искал повсюду ответы, но не нашел ни одного, у которого есть моя проблема.
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')
Я сузил его до значения main.py в скрипте запуска GUI класс под функцией usgru, где он говорит:
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])
Код работает так, как задумано, когда строка, в которой активна команда chngTOmm, но когда команда является лямбда-выражением i = i: tredugm.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