Exception in Tkinter callback Traceback (most recent call last): File…
- User
Exception in Tkinter callback Traceback (most recent call last): File “C:\Users\Slarpheus\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py”, line 1921, in call return self.func(*args) File “c:\Users\Slarpheus\python\practice.py”, line 21, in clicked1 k = random.randint(0, 1) AttributeError: ‘builtin_function_or_method’ object has no attribute ‘randint’
- Assistant
This error occurs because the
randommodule is not imported correctly in your code. To fix this, you need to import therandommodule by adding the following line at the beginning of your script:import randomHere's the corrected code:
import random from tkinter import * root = Tk() def clicked1(): k = random.randint(0, 1) # Rest of your code btn1 = Button(root, text='Button 1', command=clicked1) btn1.pack() root.mainloop()Make sure to import the required modules correctly to avoid any attribute errors.
- User
already done
- Assistant
In that case, the issue might be due to the incorrect installation or configuration of Python. Here are a few possible solutions you can try:
-
Check your Python installation: Make sure you have installed Python correctly and it is accessible from the command line. You can check this by running
python --versionin the command prompt or terminal.- If you have multiple versions of Python installed, ensure that you are using the correct version.
-
Check your Python environment: If you are using a virtual environment, make sure that you have activated it correctly before running the script.
-
Verify the integrity of the
randommodule: It's possible that therandommodule has been modified or corrupted. You can try reinstalling Python or reinstalling the module separately using the following command:python -m pip install --upgrade --force-reinstall random -
Rename your script file: Sometimes, the issue can be related to the name of the script file conflicting with other installed modules. Try renaming your script to something different and run it again.
-
Check for conflicting module names: Ensure that there are no other modules or files with the same name
randomin the same directory as your script. This can cause conflicts and interfere with the correct import of therandommodule.
If none of these solutions work, please provide more information or the code causing the issue, so we can assist you further.
-
- User
import random import numpy as np import tkinter as tk from tkinter import * from pylab import *
def clicked1(): G=0 #число поколений A1=float(txt4.get()) A2=float(txt5.get()) Z=int(txt6.get()) #кол-во организмов N=int(txt1.get()) #кол-во генов Pm=float(txt9.get()) #вероятность мутации Pvm=float(txt10.get()) #вероятность выживания более приспособленного после мутации Pv=float(txt11.get()) Q=int(txt8.get())/2
Species = np.zeros((2*Z,N),dtype=np.int32) for i in range(Z): for j in range(N): #k = random.randint(0, 1) Species[i][j] = random.randint(0, 1) #генерация Z случайных организмов while(G<txt7.get()): #A1=0.1 #A2=0.9 #Z=100 #кол-во организмов #N=10 #кол-во генов #Pm=0.01 #вероятность мутации #Pvm=0.99 #вероятность выживания более приспособленного после мутации #Pv=0.95 #вероятность замены на более приспособленного после дуэли Values_f = np.zeros((N),dtype=np.int32) for i in Values_f: Values_f[i]=random.randint(0, 15) Weights_f = np.zeros((N),dtype=np.int32) for i in Weights_f: Weights_f[i]=random.randint(0, 15) def Fitness(A): z1 = 0 z2 = 0 for i in range(N): if A[i] == 1: z1 += Values_f[i] z2 += Weights_f[i] z = A1 * z1 - A2 * z2 return z FlagParents=np.zeros(Z,dtype=bool) d = N / 10.0 Sz = int(d) Lmin = Sz # наименьшая и наибольшая точка разреза хромосомы Lmax = N - Sz for i in range(Z): FlagParents[i] = False # вначале все особи могут быть родителями # воспроизводство z - число особей + потомков, q - число потомков z = Z # вначале потомков нет q = 0 P1 = np.zeros((N),dtype=np.int32) P2 = np.zeros((N),dtype=np.int32) while q < Q: k1 = random.randint(0, Z-1) k2 = random.randint(0, Z-1) if FlagParents[k1] or FlagParents[k2] or k1 == k2: continue # построение двух потомков k = Lmin + int((Lmax - Lmin) * random.random()) # обмен хромосон for i in range(0,k): P1[i]=Species[k1][i] for i in range(k,N): P1[i]=Species[k2][i] #P1 = Species[k1][:k] + Species[k2][k:] for i in range(0,k): P2[i]=Species[k2][i] for i in range(k,N): P2[i]=Species[k1][i] #P2 = Species[k2][:k] + Species[k1][k:] Species[z] = P1[:] Species[z + 1] = P2[:] z += 2 FlagParents[k1] = True # эти родителями уже были FlagParents[k2] = True q += 1 #воспроизводство for z in range(Z + 2 * Q): # по всем организмам P1 = Species[z].copy() P2 = P1.copy() # P1 исходная особь P2 - мутант for i in range(N): d = random.random() if d < Pm: # мутация if P2[i] == 1: P2[i] = 0 else: P2[i] = 1 f1 = Fitness(P1) # приспособленность f2 = Fitness(P2) d = random.random() if f1 > f2: if d < Pvm: # останется более приспособленный # с вероятностью Pvm Species[z] = P1.copy() else: Species[z] = P2.copy() else: if d < Pvm: Species[z] = P2.copy() else: Species[z] = P1.copy() #мутация FlagDuel = np.zeros((2*Q+Z),dtype=np.bool_) FlagDelete = np.zeros((2*Q+Z),dtype=np.bool_) for i in range(Z + 2 * Q): FlagDuel[i] = False # вначале в дуэли не участвовали FlagDelete[i] = False # пока все живы z = Z + 2 * Q q = z while z > Z: # пока не останется снова Z организмов k1 = random.randint(0, q-1) k2 = random.randint(0, q-1) if FlagDuel[k1] or FlagDuel[k2] or k1 == k2: continue if FlagDelete[k1] or FlagDelete[k2]: continue # выбор двух дуэлянтов k1 k2 FlagDuel[k1] = True FlagDuel[k2] = True for i in range(N): P1[i] = Species[k1][i] for i in range(N): P2[i] = Species[k2][i] # приспособленность дуэлянтов f1 = Fitness(P1) f2 = Fitness(P2) # побеждает более приспособленный с вероятностью Pv d = random.random() if f1 > f2: if d < Pv: # delete k2 FlagDelete[k2] = True else: # delete k1 FlagDelete[k1] = True else: if d < Pv: # delete k1 FlagDelete[k1] = True else: # delete k2 FlagDelete[k2] = True z -= 1 #удаление с флагом delete SpeciesTmp = np.zeros((Z,N),dtype=np.int32) z = 0 for k in range(Z + 2 * Q): if FlagDelete[k]: continue for i in range(N): SpeciesTmp[z][i] = Species[k][i] z += 1 for k in range(Z): for i in range(N): Species[k][i] = SpeciesTmp[k][i] #нахождение лучшего организма P1 = Species[0].copy() BestP = Species[0].copy() BestValue = Fitness(P1) for k in range(1, Z): P1 = Species[k].copy() d = Fitness(P1) if d > BestValue: BestValue = d BestP = P1.copy() #естественный отбор G+=1window = Tk() window.title("Genetic algorithm")
lb1 = Label(window, text="Размерность:") lb1.grid(column=0, row=0, pady=10, padx=10) txt1 = Entry(window,width=10)
txt1.grid(column=1, row=0, pady=10, padx=10)
lb2 = Label(window, text=" Мин. размер/ценность:") lb2.grid(column=2, row=0, pady=10, padx=10) txt2 = Entry(window,width=10)
txt2.grid(column=3, row=0, pady=10, padx=10) # lb3 = Label(window, text=" Макс. размер/ценность:") lb3.grid(column=4, row=0, pady=10, padx=10) txt3 = Entry(window,width=10)
txt3.grid(column=5, row=0, pady=10, padx=10) #lb4 = Label(window, text="A1:") lb4.grid(column=0, row=1, pady=10, padx=10) txt4 = Entry(window,width=10)
txt4.grid(column=1, row=1, pady=10, padx=10) lb5 = Label(window, text="A2:") lb5.grid(column=2, row=1, pady=10, padx=10) txt5 = Entry(window,width=10)
txt5.grid(column=3, row=1, pady=10, padx=10)
lb6 = Label(window, text="Организмов:") lb6.grid(column=4, row=1, pady=10, padx=10) txt6 = Entry(window,width=10)
txt6.grid(column=5, row=1, pady=10, padx=10)lb8 = Label(window, text="Потомков:") lb8.grid(column=0, row=2, pady=10, padx=10) txt8 = Entry(window,width=10)
txt8.grid(column=1, row=2, pady=10, padx=10) #потомков lb9 = Label(window, text="Вероятность мутации:") lb9.grid(column=2, row=2, pady=10, padx=10) txt9 = Entry(window,width=10)
txt9.grid(column=3, row=2, pady=10, padx=10) # lb7 = Label(window, text="Поколений:") lb7.grid(column=4, row=2, pady=10, padx=10) txt7 = Entry(window,width=10)
txt7.grid(column=5, row=2, pady=10, padx=10)lb10 = Label(window, text="Вер-ть победы исх/мутант:") lb10.grid(column=0, row=3, pady=10, padx=5) txt10 = Entry(window,width=10)
txt10.grid(column=1, row=3, pady=10, padx=10) #потомков lb11 = Label(window, text="Вер-ть победы в дуэли:") lb11.grid(column=2, row=3, pady=10, padx=5) txt11 = Entry(window,width=10)
txt11.grid(column=3, row=3, pady=10, padx=10) #вероятность мутацииbtn1 = tk.Button(window, text="Генерировать", command=clicked1) btn1.grid(column=6, row=0, pady=10, padx=50)
window.geometry('1200x700') window.mainloop()
- Assistant
The issue in your code is most likely caused by the line
G<txt7.get(). Thetxt7variable is anEntrywidget, which returns a string when you call theget()method. However, you need to compare it with an integer in thewhileloop.To fix this, you can convert the value of
txt7.get()to an integer using theint()function. Additionally, you need to convert thetxt7variable to anEntrywidget instead of usingtxt7.get()directly.Here's the corrected line of code:
while G < int(txt7.get()): # Convert txt7.get() to an integerMake sure to update this line wherever you are using
txt7.get()as an integer comparison in your code.With this modification, the code should run without the
AttributeErroryou encountered. - User
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Slarpheus\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "c:\Users\Slarpheus\python\practice.py", line 22, in clicked1 Species[i][j] = random.randint(0, 1) AttributeError: 'builtin_function_or_method' object has no attribute 'randint'
- Assistant
The error suggests that there is an issue with the
random.randint()function. This error occurs when therandommodule is overridden by a variable or function with the same name.To resolve this issue, check your code for any variable or function named
randomthat might be conflicting with therandommodule. Make sure you haven't assigned any other value to therandomvariable or imported a module with the same name.Additionally, make sure that the
randommodule is imported correctly. It should be imported with the lineimport randomat the beginning of your script.If you have any variables or functions named
random, rename them to something else to avoid conflicts with therandommodule.