Assign bool True/False to button

Questions and answers about 3Dconnexion devices on Windows.

Moderator: Moderators

Post Reply
karel.penicka
Posts: 2
Joined: Thu Oct 24, 2024 7:13 am

Assign bool True/False to button

Post by karel.penicka »

Hi , I want to set up button , to write me in TXT file True or False , but I dont know how can I this python code use with button.

Code: Select all

file_path = r"C:\Users\karel\Documents\symbol\karel.txt"

# Otevření souboru pro čtení
try:
    with open(file_path, "r") as file:
        current_value = file.readline().strip()  # Načte první řádek a odstraní bílé znaky
except FileNotFoundError:
    current_value = "False"  # Pokud soubor neexistuje, defaultně nastavíme False

# Změna hodnoty
new_value = "False" if current_value == "True" else "True"

# Otevření souboru pro zápis a zapsání nové hodnoty
with open(file_path, "w") as file:
    file.write(new_value + "\n")
When I use .bat file I everytime see black command task.
Can you help me guys ?

Code: Select all

bat
python "C:\Users\karel\Documents\symbol\muj_skript.py"
karel.penicka
Posts: 2
Joined: Thu Oct 24, 2024 7:13 am

Re: Assign bool True/False to button

Post by karel.penicka »

This is the solution with .vbs file

Code: Select all

Dim fso, file, filePath, currentValue, newValue, lineNumber
lineNumber = 1  ' Set the line number to work with (1 for the first line, 2 for the second, etc.)

filePath = "C:\Users\karel\Documents\symbol\karel.txt"
Set fso = CreateObject("Scripting.FileSystemObject")

' Load all lines from the file into an array
Dim lines()
ReDim lines(0)

If fso.FileExists(filePath) Then
    Set file = fso.OpenTextFile(filePath, 1)
    
    Do Until file.AtEndOfStream
        lineContent = file.ReadLine
        If Trim(lineContent) <> "" Then  ' Skip empty lines
            ReDim Preserve lines(UBound(lines) + 1)
            lines(UBound(lines) - 1) = lineContent
        End If
    Loop
    file.Close
Else
    ' If the file does not exist, set default values for 8 lines
    ReDim lines(7)
    For i = 0 To 7
        lines(i) = "False"
    Next
End If

' If the specified line exists, load its value; otherwise, initialize it as "False"
If lineNumber <= UBound(lines) + 1 Then
    currentValue = Trim(lines(lineNumber - 1))
Else
    currentValue = "False"
    ReDim Preserve lines(lineNumber - 1)
    lines(lineNumber - 1) = "False"
End If

' Toggle the value for the specified line
If currentValue = "True" Then
    newValue = "False"
Else
    newValue = "True"
End If

lines(lineNumber - 1) = newValue

' Write all lines back to the file, skipping empty lines
Set file = fso.OpenTextFile(filePath, 2, True)
For Each line In lines
    If Trim(line) <> "" Then  ' Skip empty lines when writing
        file.WriteLine line
    End If
Next
file.Close
Post Reply