VS 代码不能正确调试 python [英] VS code does not debug python correctly

查看:59
本文介绍了VS 代码不能正确调试 python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 python 制作一个应用程序.但是当我尝试在 VS 代码中运行它时,它会在 VS 代码中抛出一个错误,如下所示:

I am trying to make an application with python. But when I try to run it in VS code, it throws an error with VS code as follows:

但是当我在 VS 代码之外运行代码时,它运行得非常好.见下文:

But when I run the code outside VS code, it works perfectly fine. see below:

我遇到的问题与文件目录有关.我可以这么说,因为它也发生在我的音频文件中.我不确定这里发生了什么或我做错了什么.

The problem that I get is related to file directories. I can say that because it also happens with my audio files. I am not sure what is happening here or what I am doing wrong.

奇怪的是,当我输入主文件夹的名称时,目录中包含 python 脚本,如下所示:

The weird thing about this is that when I enter my main folder's name that has the python script in the directory like this:

window.iconbitmap("cps/resources/icon/cps.ico")

仅适用于 VS 代码,但是它在 VS 代码之外不起作用.我超级困惑.

It works in VS code only, but then it does not work outside VS code. I am super confused.

在这两种情况下,我都使用 python 3.9 作为解释器.

I am using python 3.9 as interpreters in both the cases.

这是程序的完整代码

import tkinter as tk                        
from tkinter import *
import ctypes
import os
from PIL import ImageTk
from pygame import mixer
ctypes.windll.shcore.SetProcessDpiAwareness(True)

memory = []

if os.path.isfile('history.txt'):
    with open ('history.txt', 'r') as f:
        hcps = f.read()
        hcps = hcps.split(',')
        for i in hcps:
            memory.append(i)
for space in range(len(memory)):
    if memory[space] == '':
        memory.remove('')

if os.path.isfile('HS.duffy'):
    with open('HS.duffy','r') as f:
        current_HS = f.read()
        print(current_HS)

root = tk.Tk()
root.iconbitmap("resources/icon/CPS.ico")
root.geometry("600x600")
root.minsize(600,600)
root.maxsize(600,600)
root.title("CPS Tester")
sloth = ImageTk.PhotoImage(file="resources/animals/sloth.png")
panda = ImageTk.PhotoImage(file="resources/animals/panda.png")
turtle = ImageTk.PhotoImage(file="resources/animals/turtle.png")
buffalo = ImageTk.PhotoImage(file="resources/animals/buffalo.png")
rabbit = ImageTk.PhotoImage(file="resources/animals/rabbit.png")
tiger = ImageTk.PhotoImage(file="resources/animals/tiger.png")
cheetah = ImageTk.PhotoImage(file="resources/animals/cheetah.png")
global counter
counter = 0
global clicks
clicks = 0
global pos
global mainButton

global seconds
seconds = 1
mixer.init()

def finish():
    mixer.music.set_volume(0.3)
    mixer.music.load("resources/music/dj.mp3")
    mixer.music.play()

def one():
    global seconds
    seconds = 1
    entry.config(state=NORMAL)
    entry.delete(0,END)
    entry.insert(0,1)
    entry.config(state=DISABLED)

def five():
    global seconds
    seconds = 5
    entry.config(state=NORMAL)
    entry.delete(0,END)
    entry.insert(0,5)
    entry.config(state=DISABLED)


def ten():
    global seconds
    seconds = 10
    entry.config(state=NORMAL)
    entry.delete(0,END)
    entry.insert(0,10)
    entry.config(state=DISABLED)


def again():
    global aga
    global Fra
    global counter
    global clicks
    counter = 0
    clicks = 0
    aga.destroy()
    Fra.destroy()
    mixer.music.fadeout(500)

def complete():
    global current_HS
    global aga
    global Fra
    global counter
    counter = 10000000000000000000000000
    aaa = (int(clicks))
    aaaa = int(aaa)/int(entry.get())
    if aaaa == 1:
        aaaa = 1
    if aaaa == 2:
        aaaa = 2
    if aaaa == 3:
        aaaa = 3
    if aaaa == 4:
        aaaa = 4
    if aaaa == 5:
        aaaa = 5
    if aaaa == 6:
        aaaa = 6
    if aaaa == 7:
        aaaa = 7
    if aaaa == 8:
        aaaa = 8
    if aaaa == 9:
        aaaa = 9
    if aaaa == 10:
        aaaa = 10
    if aaaa == 11:
        aaaa = 11
    if aaaa == 12:
        aaaa = 12
    if aaaa == 13:
        aaaa = 13
    if aaaa == 14:
        aaaa = 14
    if aaaa == 15:
        aaaa = 15
    if aaaa == 16:
        aaaa = 16
    if aaaa == 17:
        aaaa = 17
    la.config(text=f"CPS:-{aaaa}")
    Fra = tk.Frame(mainButton, bg="#4e5d84")
    Fra.place(relheight=0.8,relwidth=0.8,relx=0.1,rely=0.1)
    aga = tk.Button(Fra,text="TRYAGAIN!!",command=again,bg='red',fg='white',border=0,borderwidth=0,activebackground="red",activeforeground="white")
    aga.pack(fill=X,side=BOTTOM)
    la2 = tk.Label(Fra,bg="#4e5d84",fg="white",font="bangers 15")
    la2.place(rely=0.02,relx=0.15,relwidth=0.7,relheight=0.2)
    la1 = tk.Label(Fra,bg="#4e5d84",text=f"CPS:-{aaaa}",fg="white",font="bangers 15")
    la1.place(rely=0.17,relx=0.37,relwidth=0.23,relheight=0.1)
    la4 = tk.Label(Fra,bg="#4e5d84",)
    la4.place(rely=0.3,relx=0.1,relwidth=0.8,relheight=0.6)
    if aaaa >0 and aaaa <= 3:
        la2.config(text="You are a Sloth")
        la4.config(image=sloth)
    elif aaaa > 3 and aaaa <= 5:
        la2.config(text="You are a Turtle")
        la4.config(image=turtle)
    elif aaaa > 5 and aaaa <= 6:
        la2.config(text="You are a Panda")
        la4.config(image=panda)
    elif aaaa == 7:
        la2.config(text="You are a buffalo")
        la4.config(image=buffalo)
    elif aaaa == 8:
        la2.config(text="You are a Rabbit")
        la4.config(image=rabbit)
    elif aaaa == 9:
        la2.config(text="You are a Tiger")
        la4.config(image=tiger)
    elif aaaa >= 10:
        la2.config(text="You are a Cheetah")
        la4.config(image=cheetah)
        finish()
    if float(aaaa) > float(current_HS) and float(aaaa) < 10:
        mixer.music.load("resources/music/highscore.wav")
        mixer.music.set_volume(1)
        mixer.music.play()
        current_HS = aaaa
        highscore.config(text=f"highscore:-{aaaa}")
    elif float(aaaa) > float(current_HS):
        highscore.config(text=f"highscore:-{aaaa}")
    if float(aaaa) < 10 and float(aaaa) < float(current_HS):
        mixer.music.load("resources/music/complete.wav")
        mixer.music.set_volume(1)
        mixer.music.play()


    memory.append(aaaa)

def stop():
    seconds = int(entry.get()) * 1000
    if seconds > 0:
        mainButton.after(seconds,lambda: complete())
    else:
        pass

def run():
    global clicks
    clicks += 1
    if clicks == 1:
        stop()
    else:
        pass

def start(event):
    global mainButton
    global counter
    global pos
    if counter == 0:
        counter = 1
        run()
        pos=(event.x)
        pos1=(event.y)
        mainButton.create_oval((pos-11),(pos1-11),(pos+11),(pos1+11),outline="lime",width=2,)
        mainButton.after(30,lambda: mainButton.create_oval((pos-20),(pos1-20),(pos+20),(pos1+20),outline="lime",width=2))
        mainButton.after(62,lambda: mainButton.delete('all'))

    elif counter < 10000000000000000000000000:
        run()
        pos=(event.x)
        pos1=(event.y)
        mainButton.create_oval((pos-11),(pos1-11),(pos+11),(pos1+11),outline="lime",width=2,)
        mainButton.after(30,lambda: mainButton.create_oval((pos-20),(pos1-20),(pos+20),(pos1+20),outline="lime",width=2))
        mainButton.after(62,lambda: mainButton.delete('all'))
        counter += 1

canvas = tk.Canvas(root,bg="red",highlightthickness=0)
canvas.place(relheight=1,relwidth=1)

la = tk.Label(canvas,bg="red",text="CPS:-",fg="white")
la.place(relx=0.35)

entry = tk.Entry(canvas,bg="#262626",fg="cyan",state=DISABLED,disabledbackground="#262626",disabledforeground="cyan")
entry.place(relx=0.64,rely=0.01)
highscore = tk.Label(canvas,bg="red",fg="white",text="highscore:-",font="courier 10")
highscore.place(relx=0.64,rely=0.058,relheight=0.043,)
entry.config(state=NORMAL)
entry.insert(0,1)
entry.config(state=DISABLED)
highscore.config(text=f"highscore:-{current_HS}")

classs = tk.Label(canvas,bg="red",fg="white",text="Duration:")
classs.place(relx=0.01,rely=0.04)

ones = tk.Button(canvas, bg="red",fg="white",text="1 second",command=one,activeforeground="white",activebackground="red")
ones.place(relx=0.15,rely=0.045,relheight=0.05)
fives = tk.Button(canvas, bg="red",fg="white",text="5 second",command=five,activeforeground="white",activebackground="red")
fives.place(relx=0.3,rely=0.045,relheight=0.05)
tens = tk.Button(canvas, bg="red",fg="white",text="10 second",command=ten,activeforeground="white",activebackground="red")
tens.place(relx=0.45,rely=0.045,relheight=0.05)
mainButton = tk.Canvas(canvas,bg="black", border=0, borderwidth=0,)
mainButton.place(relheight=0.9,relwidth=1,rely=0.1)

mainButton.bind("<Button-1>", start)
root.mainloop()
print(memory)

with open('history.txt','w+') as f:
    for cps in reversed(memory):
        if cps == '':
            pass
            print('dady-yankee')
        else:
            f.write(str(cps) + ',')
for cps in memory:
    if float(cps) > float(current_HS):
        with open ('HS.duffy','w') as f:
            f.write(str(cps))

推荐答案

我认为您说的对,问题与文件目录有关.这是因为代码中的所有文件路径都相对于当前工作目录 (CWD),因此只有当它是根文件夹时才会正确.显然,当您从 VS Code IDE 运行代码时,情况并非如此.要解决问题,无论 CWD 是什么,您都需要使其工作,为此您需要在运行时确定它们的绝对路径.

I think you're right that the problem is related to file directories. It's because all file paths in your code are relative to the current working directory (CWD), so will only be correct when that's the root folder. Apparently this is not the case when you run the code from the VS Code IDE. To fix things you need to make it work regardless of what the CWD is, and to do that you will need to determine their absolute paths at runtime.

我真的不知道你的文件夹结构是什么,所以假设它是这样的:

I don't really know what your folder structure is, so have assumed it's something like the following:

CPS
│   CPStest.py
│   history.txt
│
└───resources
    ├───animals
    │       panda.png
    │       sloth.png
    │       turtle.png
    │       ...
    │
    └───icon
            CPS.ico

如果这是正确的,那么您可以在运行时通过从包含当前执行脚本路径的内置 __file__ 变量中提取根文件夹的路径来确定绝对文件路径.获得此根文件夹的路径后,确定其他文件的路径就相对容易了.

If this is correct, then you can determine the absolute file paths at runtime by extracting the root folder's path from the built-in __file__ variable which contains the path to currently executing script. Once you have the path to this root folder, it's relatively easy to determine the paths to the other files.

在下面的示例代码中,我使用了 pathlib 模块可以做所有事情,因为它是面向对象的,并且使执行所需的步骤非常直观和可读.

In the example code below I'm using the pathlib module to do everything because it's object-oriented and makes doing the steps required very intuitive and readable.

import os
from pathlib import Path
from PIL import ImageTk
import tkinter as tk


# Determine paths based on location of this script.
main_folder_path = Path(__file__).resolve().parent
resources_path = main_folder_path / "resources"
icon_path = resources_path / "icon"
animals_path = resources_path / "animals"

if (main_folder_path / "history.txt").exists():
    print("history.txt exists")
    # (main_folder_path / "history.txt").open('r') as f:
    #     ...

root = tk.Tk()
root.iconbitmap(icon_path / "CPS.ico")
root.geometry("600x600")
root.minsize(600, 600)
root.maxsize(600, 600)
root.title("CPS Tester")

sloth = ImageTk.PhotoImage(file=animals_path / "sloth.png")
panda = ImageTk.PhotoImage(file=animals_path / "panda.png")
turtle = ImageTk.PhotoImage(file=animals_path / "turtle.png")
buffalo = ImageTk.PhotoImage(file=animals_path / "buffalo.png")
rabbit = ImageTk.PhotoImage(file=animals_path / "rabbit.png")
tiger = ImageTk.PhotoImage(file=animals_path / "tiger.png")
cheetah = ImageTk.PhotoImage(file=animals_path / "cheetah.png")
...

这篇关于VS 代码不能正确调试 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆