I use this command to build my program,it generate an exe file that work well.but it always starts with cmd console program when tk program is running.How to avoid that happen?
python -m nuitka --mingw64 *.py
if I use --windows-disable-console command,it will generate a exe file that cannot not show tk program properly.
#encoding=utf-8
import tkinter
from tinter import *
import datetime
import sys,io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
class Example(object):
"""docstring for"""
def __init__(self, date):
self.date = date
def main_gui(self):
parent=Tk()
parent.resizable(width=False, height=False)
parent.title("incomeoutcome")
parent.mainloop()
today=datetime.date.today()
ins_bill=Example(today)
ins_bill.main_gui()
Delete the linesys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') ,and all program will be run correctly.This line of code only help show utf-8 character in emulator.
Related
import pyttsx3
import speech_recognition as sr
from tkinter import *
from PIL import Image,ImageTk
from customtkinter import *
def micro():
global statement
r=sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source=source)
audio=r.listen(source)
r.energy_threshold=200
r.pause_threshold=0.5
try:
statement=r.recognize_google(audio)
except Exception as e:
statement=" "
engine.say("Pardon me ,please say that again")
engine.runAndWait()
def text_fill():
micro()
text_area.insert("end"," "+ statement)
def main():
global root,label,frame1,engine,image1
root=CTk()
root.geometry("700x600")
root.resizable(0,0)
root.title("Notepad")
frame1=CTkFrame(root,width=150,height=580)
frame1.pack_propagate(False)
frame1.place(x=10,y=10)
set_appearance_mode("dark")
set_default_color_theme("green")
engine=pyttsx3.init()
label=CTkLabel(root,text="File",width=520,height=40,font=("Algerian",30))
label.place(x=170,y=10)
global S
global text_area
text_area=CTkTextbox(root,height=580,width=520,)
text_area.place(x=170,y=60)
image1=CTkImage(Image.open("microphone.png"),size=(26,26))
micro_button=CTkButton(root,image=image1,width=10,height=10,text="",command=text_fill)
micro_button.place(x=650,y=15)
root.update()
root.mainloop()
if __name__=="__main__":
main()
I have converted this program into a .exe file using pyinstaller.
Whenever I run the normal program, i got to see a microphone in the taskbar and the program is running smoothly but when I run its exe file no microphone is shown in the taskbar and thus I am unable to provide input using voice.
Is there a way to change WM_CLASS of showinfo (and other dialogs)? className, class_ parameters do the job for Tk, Toplevel.
import tkinter as tk
from tkinter.messagebox import showinfo
if __name__ == '__main__':
root = tk.Tk(className='ymail')
mail_client = tk.Toplevel(root, class_='ymail')
new_message = tk.Toplevel(root, class_='ymail')
showinfo(title="Cancel sending", parent=new_message, message="""
Send is cancelled due to empty message""")
root.mainloop()
For showinfo dialog
$ xprop WM_CLASS
gives
WM_CLASS(STRING) = "__tk__messagebox", "Dialog"
I think it is convenient to cycle tkinter windows with Alt-~ (Tilde), for which their WM_CLASS shall be the same.
I did the search ("tkinter change WM_CLASS showinfo"). Some of the hits are not applicable, some don't work (xdotool), and some I'd rather use as a last resort (converting C program to python).
Using
Debian 10
python 3.7.3
GNOME 3.30.1
EDIT
Added workaround (using xdotool)
import threading
import subprocess
import time
import tkinter as tk
from tkinter.messagebox import showinfo
def change_dialog_class(from_="Dialog", to_="ymail"):
cmd = f"xdotool search --class {from_} set_window --class {to_}"
time.sleep(1)
subprocess.run(cmd.split())
if __name__ == '__main__':
root = tk.Tk(className='ymail')
mail_client = tk.Toplevel(root, class_='ymail')
new_message = tk.Toplevel(root, class_='ymail')
tk.Frame.class_ = 'ymail'
threading.Thread(target=change_dialog_class, args=("Dialog", "ymail"),
daemon=True).start()
showinfo(title="Cancel sending", parent=new_message,
message="""Send is cancelled due to empty message""")
root.mainloop()
along with ymail.desktop it works
$ cat ~/.local/share/applications/ymail.desktop
[Desktop Entry]
Type=Application
Terminal=false
Name=ymail
Icon=python
StartupWMClass=ymail
yet, the python solution would be better
Since I'm not a XSystem user it took me some time to follow up. It
seems like that you are looking for wm_group and unfortunately it isnt
possible without subclassing it, which results in pretty much the same
as writing your own class with tk.Toplevel. Anyway I hope
toplevel.wm_group(root) ease things out and works for you.
After I noticed that the SimpleDialog may has some functionality that you want to keep and can be hard to code for yourself, I decided to write an answer that you may want to use. It also provides the class_ option in case wm_group dosent work for you.
Here is the code:
import tkinter as tk
import tkinter.simpledialog as simpledialog
class MessageBox(simpledialog.SimpleDialog):
def __init__(self, master,**kwargs):
simpledialog.SimpleDialog.__init__(self,master,**kwargs)
#root.tk.call('wm', 'group', self.root._w, master)
def done(self,num):
print(num)
self.root.destroy()
root = tk.Tk()
MessageBox(root,title='Cancel',text='Im telling you!',class_='ymail',
buttons=['Got it!','Nah'], default=None, cancel=None)
root.mainloop()
and here is the source:
https://github.com/python/cpython/blob/main/Lib/tkinter/simpledialog.py#L31
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebKit import *
from PyQt5.QtWebKitWidgets import *
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
import sys
import os
class Navigation(QWidget):
def __init__(self):
super().__init__()
self.web = QWebView()
self.web.settings().setAttribute(QWebSettings.
JavascriptEnabled,True)
#self.web.settings().setAttribute(QWebSettings.
# JavascriptCanOpenWindows, True)
self.web.settings().setAttribute(QWebSettings.
JSAC, True)
#self.web.settings().setAttribute(QWebSettings.
#DeveloperExtrasEnabled, True)
filepath = os.path.join(
os.path.dirname(__file__), 'MapSite.html')
self.web.show()
self.web.load(QUrl.fromLocalFile(filepath))
app = QApplication(sys.argv)
ex= Navigation()
app.exec_()
This PyQt program display a webpage only when run from IDLE for python3. When I run this program fom command line or make a Navigation class object by importing in other files, the webpage not displayed, just white screen
EDIT
pi#raspberrypi:~/RaspiCallSystem4 $ python3 navigation.py
libEGL warning: DRI2: failed to authenticate
qt5ct: using qt5ct plugin
qt5ct: D-Bus system tray: no
when I execute from command line It give above output, web window starts but with white page only, running from IDLE executes smoothly
As the following answer indicates in some cases the command os.path.dirname(__file__) can return an empty string, and that's the case of the terminal, so there are 2 possible solutions:
filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MapSite.html')
Or:
filepath = QDir.current().absoluteFilePath('MapSite.html')
My function was working perfectly fine few minutes ago. Did not modify the code, just installed PyAudio. I get the error as per subject. It doesn't matter if run it from command line or IDE, same error. Any ideas?
def DataFinder():
#imports and initialize
import pandas as pd
import tkinter as tk
finder = tk.Tk()
finder.withdraw()
__dataFlag = False
#ask user to select a file
__path = tk.filedialog.askopenfilename()
#check the extension to handle reader
#for csv files
if __path.endswith('.csv')==True:
df = pd.read_csv(__path,header=0)
return df
__dataFlag = True
#and for excel files
elif __path.endswith('.xls')==True:
df = pd.read_excel(__path,header=0)
return df
__dataFlag = True
#if a file is not a supported type display message and quit
else:
__dataFlag = False
#check if there is a data to be returned
if __dataFlag==True:
return df
else:
print('The file format is not supported in this version.')
Explicitly import of filedialog can solve the problem.
So, you just need to add this line to your codes:
import tkinter.filedialog
You can find more information at Why tkinter module raises attribute error when run via command line but not when run via IDLE?
the following code didn't work for me:
import tkinter as tk
import tkinter.filedialog
But the following did work:
import tkinter
import tkinter.filedialog
and also this:
import tkinter.filedialog
import tkinter as tk
Hope this helps
Note
As mentioned by Vaidøtas I., you can't import filedialog from tkinter. Because you did not import the original tkinter but an aliased version tk.
I just installed PyCharm and opened up a script I had been using in IDLE that did some string manipulation then copied it to the clipboard, but it doesn't work when I run it in PyCharm.
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append("test")
r.destroy()
When I run this in IDLE I am able to paste "test" after, but in PyCharm it just says "Process finished with exit code 0" but there is nothing in the clipboard (even if there was before running). I have Python 3.5 as the selected interpreter.
There seems to be problem if the clipboard is manipulated and the program closes too quickly soon after. The following program worked for me but was unreliable when the call to root.after only used one millisecond for the delay. Other possibilities were tried, but code down below should work:
import random
import string
import tkinter
def main():
root = tkinter.Tk()
root.after_idle(run_code, root)
root.after(100, root.destroy)
root.mainloop()
def run_code(root):
root.withdraw()
root.clipboard_clear()
root.clipboard_append(''.join(random.sample(string.ascii_letters, 10)))
print('Clipboard is ready.')
if __name__ == '__main__':
main()
The following is a mildly more useful version of the program and demonstrates that you can make many calls to root.after_idle to run your code in a sequential manner. Its design is primarily for use to process command-line arguments and send them to your clipboard for you:
import sys
import tkinter
def main(argv):
root = tkinter.Tk()
root.after_idle(root.withdraw)
root.after_idle(root.clipboard_clear)
root.after_idle(root.clipboard_append, ' '.join(argv[1:]))
root.after_idle(print, 'The clipboard is ready.')
root.after(100, root.destroy)
root.mainloop()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))