Tkinter window items (widgets) not showing up even after using pack. (Python - python

I am creating a program called PythOS Pro, the successor to PythOS which I recently created. It is a package to add a graphical user interface to PythOS (which only uses a text shell) and it is in development. I had imported tkinter and decided to create a window that said 'Welcome to PythOS Pro' and the window worked. I then tried adding text in and, even after using pack, it did not show up!
This is the program's code:
import tkinter as tk
def run():
print("Importing packages. Please wait...")
import time
import random
time.sleep(2)
print("PythOS Pro is being deployed. Please wait...")
time.sleep(1)
StartSuccsess = random.randint(0, 100)
if StartSuccsess == 0:
print("""An error has occured. The system has halted. Please refer to the PythOS Pro error page on GitHub.
发生错误。系统已停止。请参考 GitHub 上的 PythOS Pro 错误页面。
Произошла ошибка. Система остановилась. Пожалуйста, обратитесь к странице ошибок PythOS Pro на GitHub.
Ein Fehler ist aufgetreten. Das System wurde angehalten. Weitere Informationen finden Sie auf der Fehlerseite von PythOS Pro auf GitHub.
Error Code / 错误代码 / Код ошибки / Fehlercode: E0006""")
else:
time.sleep(4)
main()
def main():
print("SUCCESS") # This is a placeholder. When finished, the core of PythOS Pro will be here!
Main = tk.Tk
WelcomeText = tk.Label(text="Welcome to PythOS Pro!")
WelcomeText.pack
run() # This will be for dev testing because it is tested standalone.
I know questions like this have been asked but I have used tkinter before and it worked, so I am EXTREMLY CONFUSED!
I tried using online code but even that did not work. My version of Python is 3.10.2, released on January 13 2022 (yes, a year ago!) I also tried the latest Visual Studio Code but it has no tkinter support. 😢
I was expecting for the text to show up and then have a party sending it on to GitHub!!!

mainloop will keep the window open, also () must be included in Tk()
import tkinter as tk
def run():
print("Importing packages. Please wait...")
import time
import random
time.sleep(2)
print("PythOS Pro is being deployed. Please wait...")
time.sleep(1)
StartSuccsess = random.randint(0, 100)
if StartSuccsess == 0:
print("""An error has occured. The system has halted. Please refer to the
PythOS Pro error page on GitHub.
发生错误。系统已停止。请参考 GitHub 上的 PythOS Pro 错误页面。
Произошла ошибка. Система остановилась. Пожалуйста, обратитесь к странице
ошибок PythOS Pro на GitHub.
Ein Fehler ist aufgetreten. Das System wurde angehalten. Weitere
Informationen finden Sie auf der Fehlerseite von PythOS Pro auf GitHub.
Error Code / 错误代码 / Код ошибки / Fehlercode: E0006""")
else:
time.sleep(4)
main()
def main():
print("SUCCESS") # This is a placeholder. When finished, the core of PythOS Pro will be here!
mainwindow = tk.Tk()
mainwindow.title('Welcome Text')
button = tk.Label(text='Welcome to PythOS Pro!')
button.pack()
mainwindow.mainloop()
run() # This will be for dev testing because it is tested standalone.

Edit: you're missing brace bracket at the end of .pack.
Change this:
WelcomeText.pack
to:
WelcomeText.pack()
Screenshot:

Related

Python/Tkinter: running an external app with subprocess causes tkinter to become disabled

The following very simple code (Windows) plays an mp4 movie file using subprocess and the Media Player Classic portable version.
import tkinter as tk
import subprocess
root = tk.Tk()
root.geometry("800x500")
mpcpath = 'MPC-BEPortable.exe'
moviepath = "filename.mp4"
def PlayMovie():
subprocess.call([mpcpath, moviepath])
PlayButton = tk.Button(root,text="play")
PlayButton.config(command=PlayMovie)
PlayButton.place(x=50,y=50)
root.mainloop()
It works perfectly. However, while the movie is playing, Tkinter is in a disabled state. That is, if you try to interact with the Tkinter app, Windows sends an error saying that the app is not responding. Is there a way (using subprocess or some other method) to have the media player go off and run in some other thread, and leave the Tkinter application operational?

How to update PyQT5 application for both Windows and macOS?

I have an application built with PyQT5 for both Windows and macOS. Currently, the user checks for updates by clicking the button and when there is a new update available I am redirecting them to the browser to my server to download the latest .exe (Windows) or .pkg (macOS). The issue is for say if the user downloads and installs the latest version in a different location than the previous one which will result in two instances of the same application.
I want to improve the user experience and make an auto-updater like all the established applications. When the user clicks the updates the application should download the new updates without making any hassles for the users and update the application for both the OS.
For Windows, I am using Pyinstaller to make the .exe file and then Inno Setup to make it executable. Moreover, for macOS I am using setuptools to make the .app and macOS packages app to make it executable.
It would be really great if someone could help me to implement an update feature for my PyQT5 application.
Hi there I have made a program where it can update itself, I was using tkinter, but it should work for PyQT5 if the same widgets are there. We are using GitHub for the program to download from there. Also I am on windows so I don't know if this works on mac. Here is my code:
import tkinter as tk #for you it is pyqt5
from tkinter import * #MessageBox and Button
import requests #pip install requests
import os #part of standard library
import sys #part of standard library
VERSION = 4
b1 = Button(frame, text = "Back", command = homepage)
b1.pack(ipadx= 10, ipady = 10, fill = X, expand = False, side = TOP)
checkupdate = Label(frame, text = "Looking for updates", font = ("Arial", 14))
checkupdate.pack()
try:
link = "https://raw.githubusercontent.com/SomeUser/SomeRepo/main/SomeFolder/version.txt"
check = requests.get(link)
if float(VERSION) < float(check.text):
mb1 = messagebox.askyesno('Update Available', 'There is an update available. Click yes to update.')
if mb1 is True:
filename = os.path.basename(sys.argv[0])
for file in os.listdir():
if file == filename:
pass
else:
os.remove(file)
exename = f'NameOfYourApp{float(check.text)}.exe'
code = requests.get("https://raw.githubusercontent.com/SomeUser/SomeRepo/main/SomeFolder/NewUpdate.exe", allow_redirects = True)
open(exename, 'wb').write(code.content)
root.destroy()
os.remove(sys.argv[0])
sys.exit()
elif mb1 == 'No':
pass
else:
messagebox.showinfo('Updates Not Available', 'No updates are available')
except Exception as e:
pass
Make sure you convert all the tkinter code to PyQt5 widgets. Also this is windows change the "https://raw.githubusercontent.com/SomeUser/SomeRepo/main/SomeFolder/NewUpdate.exe" to "https://raw.githubusercontent.com/SomeUser/SomeRepo/main/SomeFolder/NewUpdate.app" for mac. If this does not work comment and I will try my best to convert this to PyQt5.

Python does not create window with tkinter on doubleclik

Im using:
python 3
ubuntu 16
tkinter
nemo as file manager
I write this code:
#!/usr/bin/python
# coding=utf-8
#! python3
import tkinter as tk
# importa la libreria
mi_ventanita = tk.Tk()
# crea la ventanita
mi_ventanita.geometry("200x500")
mi_ventanita.title("Hola")
mi_frame = tk.Frame(mi_ventanita)
mi_frame.pack()
button = tk.Button(mi_frame, text='Okay', command=quit)
button.pack(side=tk.LEFT)
#Width x Height
mi_ventanita.mainloop()
And saved it in a file namede crear.py
I changed the file permissions from command line with this command:
sudo chmod a+x *.py
When in nemo I double click the file, appears a message:
I choose run in terminal
For one second appear a window border, but then dissapear...
If I run the code from terminal using:
python3 crear.py
The window appears!
If i debug the file using pdb:
python3 -m pdb crear.py
The window appears!
So my question is:
It is possible to open the window when I double click the file from nemo?
I have other python programs, which not use tinker, and work perfectly on double click using nemo as file manager.
Thank you in advance
I am not familiar with Linux of Ubuntu, but I see 2 problems:
button = tk.Button(mi_frame, text='Okay', command=quit)
The quit has to be in quotation marks
button = tk.Button(mi_frame, text='Okay', command="quit")
Commands are not built in, meaning when you pass a parameter in the command option, you are actually executing a function when the button is clicked
def quit():
return
button = tk.Button(mi_frame, text='Okay', command="quit")
A work around:
I created an sh file with this code:
#!/bin/bash
python3 crear.py
Saved and make it executable.
When i double click the sh file, python creates the window...
As acw1688 wrote, the solution was using:
#!/usr/bin/env python3
So the working code is:
#!/usr/bin/env python3
# coding=utf-8
import tkinter as tk
# importa la libreria
mi_ventanita = tk.Tk()
# crea la ventanita
mi_ventanita.geometry("200x500")
mi_ventanita.title("Hola")
mi_frame = tk.Frame(mi_ventanita)
mi_frame.pack()
button = tk.Button(mi_frame, text='Okay', command=quit)
button.pack(side=tk.LEFT)
#Width x Height
mi_ventanita.mainloop()
Thank you very much!

Bring window to focus with python periodically

import win32gui
import time
def windowEnumerationHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
if __name__ == "__main__":
top_windows = []
win32gui.EnumWindows(windowEnumerationHandler, top_windows)
for i in top_windows:
print(i)
if "zoom" in i[1].lower():
print(i, 'is found')
while True:
win32gui.ShowWindow(i[0],5)
win32gui.SetForegroundWindow(i[0])
time.sleep(1)
I've heard that zoom monitors whether the window is not in focus for more than 30 seconds, so I've been working on a way to repetitively throw it to the front while I work on other projects. The problem is the code raises an exception
0, 'SetForegroundWindow', 'No error message is available'
and the window just flashes yellow. Same problem with chrome as well. Would appreciate some help here :)
I had the same problem while I was trying to SetForegroundWindow(hwnd). The icon on the taskbar was just flashing, but the program stayed in the background. As you can read here:
https://learn.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-setforegroundwindow?redirectedfrom=MSDN
"An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user."
For me helped:
import win32gui, win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys('%')
win32gui.SetForegroundWindow(hwnd)

Why always have to force quit python launcher after running Tkinter on Mac?

I'm using jupyter notebook on mac, recently I need to write interactive dialog box, so after google, I use Tkinter to make an interactive window.
But I was bothered by this problem couples day ,and still can't find a solution way.
Fisrt example:
from Tkinter import *
from tkFileDialog import askopenfilename
import sys
import os,time
def callback():
name= askopenfilename()
print name
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Second example:
from Tkinter import *
import sys,os
class YourApp(Tk):
def quit_and_close(self):
app.quit()
#os._exit(0)
#sys.exit(1)
#exit(0)
app = YourApp()
app.title('example')
app.geometry('400x300+200+200')
b = Button(app, text = "quit", command = app.quit_and_close)
b.pack()
app.mainloop()
And the third one:
import Tkinter as tk
import tkMessageBox
def ask_quit():
if tkMessageBox.askokcancel("Quit", "You want to quit now? *sniff*"):
root.destroy()
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", ask_quit)
root.mainloop()
After running those above code, always need have to force quit python launcher.
It is very weird, and annoying because after forcing quit, I will got the error:
Is it necessary to use python launcher as default window?
Is there possible to set another window to open ?
or is there proper way to close the launcher without causing programming crash?
p.s Even I try to use wxpython, it still open python launcher and got the same problem.

Categories

Resources