I have a python code:
import turtle
import random
import matplotlib.pyplot as plt
import math
###############
myPen = turtle.Turtle()
I've installed all libraries but I have this error:
TclError: no display name and no $DISPLAY environment variable in line:
myPen = turtle.Turtle()`
Related
I recently started working on a program in python using Tkinter and now I want to open it from another file.
I have a home page file named HomePage.py that will have a button to open another file, called VirusTotalAPI.py. I didn't find any answers because when I run the program, it opens the VirusTotalAPI.py file, and if I close it the Homepage.py will run, but the button won't work and if I try to close it, it will open the HomePage.py.
#Homepage.py
from tkinter import *
import VirusTotalAPI as vt
Home_Window=Tk()
Home_Window.geometry("980x530")
Home_Window.title("VirusTotal By Carotide")
Home_Window.config(background="grey")
def Window_35_mo() :
vt.Window_35mo
Window_35_mo_open = Button()
Window_35_mo_open.config(text= "Fichier < 35 mo", command= Window_35_mo)
Window_35_mo_open.pack()
Home_Window.mainloop()
The next one is a part from the VirusTotalAPI.py because the file is too long
#VirusTotalAPI.py
import requests
import hashlib
import json
from tkinter import *
from tkinter import filedialog
import HomePage
Window_35mo = Tk()
Window_35mo.geometry("980x530")
Window_35mo.title("VirusTotal By Carotide")
Window_35mo.config(background="grey")
global files
global file_path
def retrieve_API():
API_Value=GetAPIBox.get("1.0","end-1c")
print(API_Value)
GetAPIBox=Text(Window_35mo, height=2, width=10)
GetAPIBox.pack()
API_Button=Button(Window_35mo, height=1, width=10, text="YourAPI",
command=lambda: retrieve_API())
API_Button.pack()
Window_35mo.mainloop()
Thank you in advance.
I tried to import it by different ways like this:
import VirusTotalAPI
Or this:
from VirusTotalAPI import *
I tried to do this too:
from tkinter import *
from VirusTotalAPI import Window_35mo
Home_Window=Tk()
Home_Window.geometry("980x530")
Home_Window.title("VirusTotal By Carotide")
Home_Window.config(background="grey")
#homepage
def winopen35mo() :
Window_35mo
Window_35_mo_open = Button()
Window_35_mo_open.config(text= "Fichier < 35 mo", command= winopen35mo)
Window_35_mo_open.pack()
Home_Window.mainloop()
And it told me this:
ImportError: cannot import name 'Window_35mo' from partially initialized module 'VirusTotalAPI' (most likely due to a circular import)
I finally found how to do it there is the solution :
First we need to import os, subprocess and sys
from tkinter import *
import os
import subprocess
import sys
Then,we declare the file path of the file, for this one it is VirusTotalAPI.py by doing so :
GUI_VirusTotalAPI_Path = 'C:\\Users\\...\\VirusTotalAPI.py'
Now we enter the args, to execute and enter the path name :
args = '"%s" "%s" "%s"' % (sys.executable,
GUI_VirusTotalAPI_Path,
os.path.basename(VirusTotalAPI))
We are almost there, now we create a function to run this using the args we previoulsy used :
def Open_GUI_VirusTotalAPI_35mo() :
proc = subprocess.run(args)
Then another function to destroy the window :
def DestroyHomeWindow() :
Home_Window.destroy
Finally we create the button and "tell" it to execute the command Open_GUI_VirusTotalAPI_35moand at the same time close the window :
Window_35_mo_open = Button()
Window_35_mo_open.config(text= "Fichier < 35 mo", command= lambda:[Home_Window.destroy(),Open_GUI_VirusTotalAPI_35mo()])
Window_35_mo_open.pack()
And this is how I did it, sorry for the poor explanation and my bad english, hope this helped some people.
When I use this code
widget.Battery(
format = 'Battery: {percent:2.0%}',
foreground = colors[2],
background = colors[5],
padding = 5
),
it Work completly Fine but when I use this code
widget.CPU(
foreground = colors[2],
background = colors[4],
threshold = 90,
padding = 5
),
at bar it shows Import Error: CPU and it happnes with memory net and all those widgets
these thing i have imported
import os
import re
import socket
import subprocess
from libqtile import *
from libqtile.config import Click, Drag, Group, KeyChord, Key, Match, Screen
from libqtile.command import lazy
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal
from typing import List
from libqtile.widget import *
You need to install all the requirements of each widget.
For example, for the CPU widget you may need the python library called psutil
You have all the information of each widget in http://docs.qtile.org/en/latest/manual/ref/widgets.html#
You need to change this line
from libqtile.widget import *
to
from libqtile import widget
For our research project, my groupmates and I created a pdf file maker code using Reportlabs package stored in a Python file named "PDFCanvas". In another Python file called "AppTest" which contains our tkinter GUI with a button, we copypasted our PDFCanvas File code to try and initialize the creation and viewing of our PDF using the button, which of course works when in a separate file. Apparently, when we run the program in "AppTest", it prompts us with the error: AttributeError: 'str' object has no attribute 'tk'. Can we ask for help as to how we can get it running?
My bad for deleting the first reference working code of the separate PDF creator but here it is:
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.units import inch, cm
from reportlab.pdfgen.canvas import *
from reportlab.lib.colors import *
from reportlab.rl_config import defaultPageSize
from reportlab.pdfbase.pdfmetrics import stringWidth
page_height = defaultPageSize[1]
page_width = defaultPageSize[0]
import os
import sys
import subprocess
import sqlite3
canvas = Canvas("Report - Name [Date].pdf")
canvas.setFont("Helvetica-Bold", 14)
canvas.drawString(72, 795.68, "Veterinary Office")
canvas.save()
subprocess.Popen(['Report - Name [Date].pdf'], shell=True)
UPDATE - Here's a sample of the code that generates the error:
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.units import inch, cm
from reportlab.pdfgen.canvas import *
from reportlab.lib.colors import *
from reportlab.rl_config import defaultPageSize
from reportlab.pdfbase.pdfmetrics import stringWidth
page_height = defaultPageSize[1]
page_width = defaultPageSize[0]
import os
import sys
import sqlite3
import subprocess
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkFont
from tkinter import *
run = tk.Tk()
def PDFPrint():
canvas = Canvas("Report - Name [Date].pdf")
canvas.setFont("Helvetica-Bold", 14)
canvas.drawString(72, 795.68, "Vet Office")
canvas.save()
subprocess.Popen(['Report - Name [Date].pdf'], shell=True)
aButton = Button(run, text = 'Print', command = PDFPrint())
run.mainloop()
For the full error stack:
Traceback (most recent call last):
File "C:\Users\Desktop\AppTest.py", line 32, in <module>
aButton = Button(run, text = 'Print', command = PDFPrint())
File "C:\Users\Desktop\AppTest.py", line 25, in PDFPrint
canvas = Canvas("Report - Name [Date].pdf")
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 2688, in __init__
Widget.__init__(self, master, 'canvas', cnf, kw)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 2566, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 2535, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
[Finished in 1.3s]
We already preinstalled the ReportLabs Library via pip. I hope I provided adequate information so that answers can be provided to this problem of ours. Thank you!
I figured it out. When importing you used:
from reportlab.pdfgen.canvas import Canvas
...
from tkinter import *
But the problem is that tkinter also defines and overrides the Canvas that was imported from reportlab. That is why you should avoid import *. To fix that issue just change it to import tkinter as tk and then add tk. everywhere you used tkinter widgets/variables. tkinter.Canvas expects a tkinter widget as the first parameter unlike reportlab.pdfgen.canvas.Canvas which expects a string.
Also change this: aButton = Button(run, text = 'Print', command = PDFPrint()) to this:
aButton = Button(run, text = 'Print', command = PDFPrint)
TL;DR You imported Canvas twice and one of the definitions was lost (the one that you wanted to use).
My project said to "Implement the class for the display of the amplitude of the wave file or frequency entered and create the method that will extract a portion of the waveform to display." I am having trouble passing the user input from one file to another without importing the entire file (tried that gave me errors)
Here's some of my main file:
import tkinter as tk
import winsound
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog``
from tkinter import simpledialog
import Create_Account
import Login_file
import Display_Waveform_Amplitude
class audioFrequencyGUI:
#...... (skipping unimportant code)
def Play(self, Hz):
self.play_frequency.config(command = lambda: winsound.Beep(Hz, 500))
#MAIN LOOP
tk.mainloop()
def Display_Waveform(self):
DisplayWindow = Display_Waveform_Amplitude.Display_Waveform_AmplitudeGUI()
DisplayWindow.amplitude_window.wait_window()
Heres Display Waveform File:
import tkinter as tk
from tkinter import*
import numpy as np
import matplotlib.pyplot as plt
class Display_Waveform_AmplitudeGUI:
def __init__(math):
math.amplitude_window = tk.Tk()
math.amplitude_window.title("Amplitude Display")
math.amplitude_window.minsize(width = 500, height = 500)
def plot_graph(math):
time = 1/frequency
x = np.arrange(0, time, 0.1)
y = frequency - 1
plt.title('Amplitude Waveform: Entering Frequencies')
plt.xlabel('Time (seconds)')
plt.ylabel('Amplitude')
plt.plot(x, y)
plt.show()
I know in my code I haven't passed anything because I simply don't know what to do. I've been moving things around and trying out different things for days. I just need to know how to pass the frequency from my main file to another file that contains another class and function. Thank you I appreciate the help!
If files are in same folder
I think you can solve this just importing the class in the main.py file into display file:
from main import audioFrequencyGUI
Now you can use funcs from main.py file inside display.py
I started having some issues with miniconda and PyCharm so I had to reinstall them. However, now when I use cx_freeze to create .exe I get the error below.
Here is my code:
from tkinter import *
from tkinter import ttk
from ttkthemes import ThemedTk
from ttkthemes import themed_tk as tk
import os
from tkinter import messagebox
import getpass
import pyodbc
import test
import time
class Application(object):
def __init__(self,master):
self.master=master
self.itemIn = ttk.Button(master, text="In", width=35,
command=self.itemIn).grid(row=2, column=0, padx=10,pady=15)
self.itemOut = ttk.Button(master, text="Out", width=35,
command=self.itemOut).grid(row=3, column=0, padx=10)
def itemIn(self):
pass
def itemOut(self):
pass
def main():
global userList
strForDB = os.getcwd() + '\DBINFO.txt'
openDBFile = open(strForDB, 'r')
currentDirForDB = openDBFile.read()
openDBFile.close()
dbPath = currentDirForDB
conToSubmit = pyodbc.connect(dbPath)
curToSubmit = conToSubmit.cursor()
userName = getpass.getuser()
root = tk.ThemedTk()
root.get_themes()
root.set_theme("radiance")
app=Application(root)
root.title("Main Menu v:5.1")
root.configure(background="#F4F3F1")
root.resizable(0, 0)
# Change Application Icon with below:
root.wm_iconbitmap(os.getcwd()+'/Z Logo.ico')
### To maximize
# w, h = root.winfo_screenwidth(), root.winfo_screenheight()
# root.geometry("%dx%d+0+0" % (w, h))
root.geometry('340x510+300+80')
root.mainloop()
#else:
# messagebox.showerror("Access Denied", "You are not allowed to access this application.")
# return
if __name__=='__main__':
main()
This is cx_freeze build script, where I have imported all the relevant modules.
import cx_Freeze
import os
from cx_Freeze import *
import sys
if sys.platform == "win32":
base = "Win32GUI"
imodules=['tkinter','pyodbc','getpass','pathlib','openpyxl','datetime','os','win32print','win32ui'] #modules to include
emodules=[] ###modules to NOT include
#(useful if a module is forcefully installed
#even if you don't want that module)
build_exe_options={"packages":imodules,"excludes":emodules}
setup(
name= "WMS System",
options={"build_exe":build_exe_options},description="App to track Inventory",author="VM",
executables=[
Executable(
"WMS.py", base=base, icon="Z logo.ico"
)
]
)
I have been using cx_freeze for quite some time but I have never seen this error.
I was having identical problem as you and after a long troubleshooting session I found out that
in /lib folder of my build i had "Tkinter" folder, renaming it to "tkinter" solved the above issue
any following errors of the type module not found could be solved by either adding them to the "includes" tag of build options or finding and copying the whole module folder yourself from python installation folder
The folder name in project must be "lib/tkinter", but maybe it is "lib/Tkinter", then you must rename the folder from "Tkinter" to "tkinter".