Pycharm – die besten Beiträge

Customtkinter?

Ist es normal dass das erstellen von Labels, Textfelder oder Buttons in Klassen als Vorlage super viel Schreibarbeit ist oder geht das auch eleganter und sauberer?

main:

maclass Main(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.main_window()
        self.chatbot_output = InputBox(self, 1, 1, 10, 10, "s", 500, 500, "#202222", "red", "white", "Gib einen Text ein...")
        self.chatbot_output.grid(row=1, column=1, pady=10, padx=10, sticky="s")
        self.chatbot_input = InputBox(self, 2, 1, 0, 10, "n", 500, 50, "#202222", "red", "white", "Gib einen Text ein...")
        self.chatbot_input.grid(row=2, column=1, pady=0, padx=10, sticky="n")
        self.placeholder = Label(self, 0, 1, 0, 10, "n", 500, 320, "transparent", "transparent", "white", ".")
        self.placeholder.grid(row=0, column=1, pady=0, padx=10, sticky="n")
    def main_window(self):
        height = 920
        width = 1680
        x = (self.winfo_screenwidth()//2)-(width//2)
        y = (self.winfo_screenheight()//2) - (height//2)
        self.geometry(f"{width}x{height}+{x}+{y}")
        self.title("YourTerminal")
        self.grid_columnconfigure(0, weight=0)
        self.grid_rowconfigure(0, weight=0)



if __name__ == "__main__":
    main = Main()
    main.mainloop()
    sys.exit()

Vorlage in einer Klasse und in einer anderen Datei:

class InputBox(ctk.CTkFrame):
    def __init__(self, master, row, column, pady, padx, sticky, width, height, entry_fg_color,frame_fg_color, textcolor, placeholder, *args, **kwargs):
        super().__init__(master, fg_color=frame_fg_color, *args, **kwargs)
        self.set_setup(row, column, pady, padx, sticky, width, height, entry_fg_color, textcolor, placeholder)

    def set_setup(self, row, column, pady, padx, sticky, width, height, entry_fg_color, textcolor, placeholder):
        self.input = ctk.CTkEntry(self,
                                  width=width,
                                  height=height,
                                  fg_color=entry_fg_color,
                                  text_color=textcolor,
                                  placeholder_text=placeholder,
                                  )
        self.input.grid(row=row, column=column, pady=pady, padx=padx, sticky=sticky)
Code, Programmiersprache, Python, Python 3, Tkinter, Pycharm

TypeError: can only concatenate str (not "function") to str?

ich möchte eine ui für mailtm erstellen aber bekomme kein output raus also wenn email ankommen werden sie nicht angezeigt und wenn ich listener eingebe bekomme ich jedes mal den gleichen fehler code

Fehler code:

TypeError: can only concatenate str (not "function") to str

from mailtm import *


def listener(message):
    print("\nSubject: " + message['subject'] + str(listener))
    print("Content: " + message['text'] if message['text'] else message['html'] + str(listener))


test = Email()
print("\nDomain: " + test.domain)

test.register()
print("\nEmail Adress: " + str(test.address))


test.start(listener, interval=3)
print("\nHab Sabr.....")


main = ctk.CTk()
main.geometry("500x320")
main.title("Temp mail By Amjn")


emaila = ctk.CTkEntry(main, placeholder_text="         " + test.address, width=900, font=("Helvetica", 20))
emaila.configure(state="readonly")
emaila._corner_radius = 10
emaila.pack()


Copyt = ctk.CTkLabel(main, text="Copy Email", font=("Helvetica", 20))
Copyt.pack()


def neuw(self=None):
    neu = ctk.CTkToplevel(main)
    neu.title("Emails              (MADE BY AMJN)")
    neu.geometry("500x320")
    neu.corner_radius = 30
    neu.resizable(width=True, height=True)

    Ausg = ctk.CTkEntry(neuw, placeholder_text=("         ") + listener, width=900, font=("Helvetica", 20))
    Ausg.pack()


knopf = ctk.CTkButton(main, text="Emails", font=("Helvetica", 20), command=neuw)
knopf.pack(pady=20)

main.mainloop()
Code, Programmiersprache, Python, UI, Python 3, Tkinter, Pycharm

SSL-Paket kann nicht installiert werden. Kann mir jemand das Problem erklären?


Servus alle zusammen.

Ich habe mal wieder eins der unnötigsten Probleme die man so gar nicht gebrauchen kann.
Vorab: Ich verwende PyCharm CommunityEdit2023

Folgende Problematik stellt sich mir:Ich versuche über den PyCharm Interpreter das Paket ssl zu laden und erhalte:

Collecting ssl

 Using cached ssl-1.16.tar.gz (33 kB)

 Using cached ssl-1.15.tar.gz (32 kB)




  ERROR: Command errored out with exit status 1:

   command: 'D:\Python\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Paddy\\AppData\\Local\\Temp\\pip-install-6xunn48y\\ssl_93be5a3dfd464eefb55e12eacc1c7aae\\setup.py'"'"'; __file__='"'"'C:\\Users\\Paddy\\AppData\\Local\\Temp\\pip-install-6xunn48y\\ssl_93be5a3dfd464eefb55e12eacc1c7aae\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Paddy\AppData\Local\Temp\pip-pip-egg-info-xz6xi0b2'

     cwd: C:\Users\Paddy\AppData\Local\Temp\pip-install-6xunn48y\ssl_93be5a3dfd464eefb55e12eacc1c7aae\

  Complete output (6 lines):

  Traceback (most recent call last):

   File "<string>", line 1, in <module>

   File "C:\Users\Paddy\AppData\Local\Temp\pip-install-6xunn48y\ssl_93be5a3dfd464eefb55e12eacc1c7aae\setup.py", line 33

    print 'looking for', f

       ^

  SyntaxError: Missing parentheses in call to 'print'. Did you mean print('looking for', f)?

  ----------------------------------------

WARNING: Discarding https://files.pythonhosted.org/packages/83/21/f469c9923235f8c36d5fd5334ed11e2681abad7e0032c5aba964dcaf9bbb/ssl-1.16.tar.gz#sha256=ac21156fee6aee9eb8d765bbb16f5f49492d81ff4b22f7b8fc001d2251120930 (from https://pypi.org/simple/ssl/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

  ERROR: Command errored out with exit status 1:

   command: 'D:\Python\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Paddy\\AppData\\Local\\Temp\\pip-install-6xunn48y\\ssl_0d4afefa00504f218b834c3475a8235c\\setup.py'"'"'; __file__='"'"'C:\\Users\\Paddy\\AppData\\Local\\Temp\\pip-install-6xunn48y\\ssl_0d4afefa00504f218b834c3475a8235c\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Paddy\AppData\Local\Temp\pip-pip-egg-info-2f8p2rk1'

     cwd: C:\Users\Paddy\AppData\Local\Temp\pip-install-6xunn48y\ssl_0d4afefa00504f218b834c3475a8235c\

  Complete output (6 lines):

  Traceback (most recent call last):

   File "<string>", line 1, in <module>

   File "C:\Users\Paddy\AppData\Local\Temp\pip-install-6xunn48y\ssl_0d4afefa00504f218b834c3475a8235c\setup.py", line 74

    print 'looking for', f

       ^

  SyntaxError: Missing parentheses in call to 'print'. Did you mean print('looking for', f)?

  ----------------------------------------

WARNING: Discarding https://files.pythonhosted.org/packages/3a/c2/846a19d1572ec6cb8ac438d58a898de8926d32e13f0355cdf4ab00864b5f/ssl-1.15.tar.gz#sha256=1266302ce62c4b60c7ca0e1d3d104ba11d2749e5881d8ac4f006cf9a0446d589 (from https://pypi.org/simple/ssl/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

ERROR: Could not find a version that satisfies the requirement ssl (from versions: 1.15, 1.16)

ERROR: No matching distribution found for ssl

WARNING: You are using pip version 21.1.3; however, version 24.0 is available.

You should consider upgrading via the 'D:\Python\python.exe -m pip install --upgrade pip' command.

Via cmd erhalte ich die gleiche Meldung.
Ich habe alle Python-Versionen schon deinstalliert, System neu gestartet und wieder installiert. Das gleiche habe ich auch mit pip probiert.

Kann mir hier vielleicht jemand weiterhelfen?

Vielen Dank und liebe Grüße im Voraus! :)

cmd, Code, Error, Python, SSL, pip, Python 3, Windows 10, Pycharm

Python Fehlermeldung "KeyError: 'data'"?

Ich möchte gerne einen KI Discord Server machen. Die KI hab ich schon und diese hat auch eine API(?). Ich hab den Bot auch schon auf dem Server und ich kann auch Prompts eingeben. Aber wenn ich Prompt eingebe, kommt bei diesem Code:

import discord
from gradio_client import Client


TOKEN = 'MeinToken'
FOOOCUS_API_URL = 'http://127.0.0.1:7865/'


fooocus_client = Client(FOOOCUS_API_URL)


intents = discord.Intents.default()
client = discord.Client(intents=intents)


@client.event
async def on_ready():
    print(f'{client.user} ist eingeloggt!')


@client.event
async def on_message(message):
    if message.channel.name == 'prompt-kanal' and message.author != client.user:
        result = fooocus_client.predict(message.content, fn_index=2)
        await message.channel.send(file=discord.File(result))


client.run(TOKEN)

Diese Fehlermeldung:

2024-04-16 15:35:07 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:...\venv\Lib\site-packages\gradio_client\compatibility.py", line 105, in _predict
output = result["data"]
~~~~~~^^^^^^^^
KeyError: 'data'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:...\venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:...\bot.py", line 19, in on_message
result = fooocus_client.predict(message.content, fn_index=2)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:...\venv\Lib\site-packages\gradio_client\client.py", line 459, in predict
).result()
^^^^^^^^
File "C:...\venv\Lib\site-packages\gradio_client\client.py", line 1374, in result
return super().result(timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users..._base.py", line 456, in result
return self.__get_result()
^^^^^^^^^^^^^^^^^^^
File "C:\Users..._base.py", line 401, in __get_result
raise self._exception
File "C:\Users...\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:...\compatibility.py", line 65, in _inner
predictions = _predict(*data)
^^^^^^^^^^^^^^^
File "C:...\compatibility.py", line 119, in _predict
raise KeyError(
KeyError: 'Could not find 'data' key in response. Response received: {'detail': [{'type': 'model_attributes_type', 'loc': ['body'], 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': '{"data": [""], "fn_index": 2, "session_hash": "d7f62bf0-174c-45fe-b3f6-c5e7f00848d3"}', 'url': 'https://errors.pydantic.dev/2.1/v/model_attributes_type'}]}'

Ich checke einfach nicht, woran das liegen könnte...

Linux, Bot, cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Pycharm, Discord, Discord Bot, ChatGPT

Warum funktioniert Flask und Websockets nicht?

Hallo,

ich wollte meinen Python- Code mit meinem HTML- Code verbinden, damit, wenn mein Wake- Word "Luna" erkannt wurde, der Hintergrund der Datei output.html seine Farbe ändert und rot wird. Hier ist der Code:

Python:

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('connect')
def handle_connect():
    print("Client verbunden")


@socketio.on('disconnect')
def handle_disconnect():
    print("Client getrennt")


@socketio.on('change_background')
def change_background(color):
    print("Hintergrundfarbe ändern:", color)
    socketio.emit('background_changed', color)

HTML /CSS:

... body {
  background-color: black;
  margin: 0;
  padding: 0;
  text-align: center;
  overflow-x: hidden;
  overflow-y: hidden;
    -webkit-user-select: none; /* Für WebKit-Browser */
    -moz-user-select: none; /* Für Mozilla-basierte Browser */
    -ms-user-select: none; /* Für Microsoft Edge */
    user-select: none;
}  
</style>
</head>
<body>

JavaScript:

... // FLASK
    var socket = io();

    socket.on('connect', function() {
        console.log('Verbunden mit dem Server');
    });

    socket.on('disconnect', function() {
        console.log('Verbindung zum Server getrennt');
    });

    socket.on('background_changed', function(color) {
        console.log('Hintergrundfarbe geändert:', color);
        document.body.style.backgroundColor = color;
    });
</script>
</body>
</html>
    """
    with open("output.html", "w") as html_file:
        html_file.write(html_content)

    return "output.html"

Wenn ich den Code aber ausführe und "Luna" sage, ändert der Hintergrund nicht seine Farbe. Woran liegt das?

Freundliche Grüsse

HTML, Webseite, JavaScript, HTML5, Code, Programmiersprache, Python, Frontend, Python 3, Pycharm, Flask

Warum funktioniert mein Code auf dem Raspberry Pi nicht?

Hallo,

Ich programmiere gerade einen Sprachassistenten und auf meinem Windows PC hat alles super funktioniert, aber als ich das Programm auf den Pi geladen und das Programm gestartet habe, kam diese Fehlermeldung:

Traceback (most recent call last):

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 1164, in <module>

  execute()

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 658, in execute

  if detect_wake_word(): # Falls das Wake-Word erkannt wurde

    ^^^^^^^^^^^^^^^^^^

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 139, in detect_wake_word

  recognizer.adjust_for_ambient_noise(source) # Hintergrundgeräusche anpassen

  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/.venv/lib/python3.11/site-packages/speech_recognition/__init__.py", line 389, in adjust_for_ambient_noise

  assert source.stream is not None, "Audio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"

      ^^^^^^^^^^^^^^^^^^^^^^^^^

AssertionError: Audio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?

Ich habe ein gutes Mikrofon am Pi, welches auch funktioniert, und ich habe schon viel am Code geändert, aber es geht nicht weg. Woran kann das sonst liegen?

Wenn ich Teile meines Codes zeigen soll, könnt ihr das sagen.

Freundliche Grüsse

cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Raspberry Pi, Pycharm, ChatGPT

Wie kann ich die Porcupine Wake-Word detection verwenden?

Hallo,

ich programmiere gerade einen Sprachassistenten und wollte nun die Wake-Word Funktion hinzufügen. Das ist mein Code:

def wait_for_wake_word(recognizer, source):
    keyword_path = r"C:\Users\User\PycharmProjects\voiceAssistant\hey-Luna_de_windows_v3_0_0 (2)\hey-Luna_de_windows_v3_0_0.ppn"
    sensitivity = 0.5
    access_key = "..."

    handle = pvporcupine.create(keywords=[keyword_path], sensitivities=[sensitivity], access_key=access_key)

    if handle is None:
        print("Fehler beim Erstellen des Porcupine-Objekts. Überprüfe den Dateipfad und den Zugriffsschlüssel.")
        return

    audio = pyaudio.PyAudio()

    try:
        print("Warte auf das Wake-Word...")

        stream = audio.open(
            rate=handle.sample_rate,
            channels=1,
            format=pyaudio.paInt16,
            input=True,
            frames_per_buffer=handle.frame_length)

        while True:
            pcm = stream.read(handle.frame_length)
            pcm = pcm[0: handle.frame_length]

            keyword_index = handle.process(pcm)
            if keyword_index >= 0:
                print("Wake-Word 'Luna' erkannt!")
                break
    finally:
        if handle is not None:
            handle.delete()
        if stream is not None:
            stream.close()
        if audio is not None:
            audio.terminate()

Wenn ich es nun aber ausführe, kommt diese Fehlermeldung:

Traceback (most recent call last):

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 1162, in <module>

  execute()

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 671, in execute

  wait_for_wake_word(recognizer, source)

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 121, in wait_for_wake_word

  handle = pvporcupine.create(keywords=[keyword_path], sensitivities=[sensitivity], access_key=access_key)

       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\pvporcupine\_factory.py", line 59, in create

  raise ValueError(

ValueError: One or more keywords are not available by default. Available default keywords are:\ngrapefruit, picovoice, terminator, americano, computer, hey siri, bumblebee, hey barista, ok google, alexa, hey google, blueberry, grasshopper, jarvis, porcupine, pico clock

Es liegt aber nicht an einem Rechtschreibfehler im Dateipfad oder im API Key. Woran kann es sonst liegen?

Freundliche Grüsse

cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Pycharm

Meistgelesene Beiträge zum Thema Pycharm