How to open a python program within python - python-2.7

I'm working on a program using tkinter (2.7) that when a button is clicked, it opens a separate python program. What I have been trying to do is give the button a command and define it as the separate program. This is what I have so far:
from Tkinter import *
from ttk import *
import os
app = Tk()
app.title("iClassics")
app.geometry("450x300+200+200")
#Definitions
def mTetris():
subprocess.Popen("Tetris.py")
#Heading
headlabel = Label(text="iClassics", font=("Times", 30), background=("blue")).pack()
#Buttons
buttontetris = Button(app, text="Tetris", command=mTetris).pack()
buttonpong = Button(app, text="Pong").pack()
buttonbrick = Button(app, text="Brick Breaker").pack()
buttonsnake = Button(app, text = "Snake").pack()
app.mainloop()
Why can't I open my tetris.py on click?

Take a look at popen.
You shoold call it this way:
subprocess.Popen(["python", "tetris.py"])

Related

Arabic text inverted in Python Tkinter

I'm trying to display Arabic text in a Tkinter program, Windows seems to display them correctly, but gets inverted in Kali Linux for some reason.
test.py file content :
# -*- coding: utf-8 -*-
from Tkinter import *
import Tkinter
import platform
root = Tk()
Label(root, text = "Python version: %s" % platform.python_version()).pack()
Label(root, text = "Tkinter version: %d" % Tkinter.TkVersion).pack()
Label(root, text = "العربية").pack()
root.mainloop()
Result in Windows 10 Pro:
Result in Kali Linux:
Same Python and Tkinter version, but different result, anyone knows the exact reason behind this?

How to create a .txt file in python by the user prefered nsme?

I have made a program tht reads the stored file details.
I want to create a .txt file using python tkinter .the name of the creating file will be given by user in entry box.
Can you provide the correct code.please
from tkinter import *
root = Tk()
def clicked():
Input = entry1.get()
FileName = str("filepath" + Input + ".txt")
TextFile = open(FileName,"w")
entry1 = Entry(root)
button1 = Button(root,text="Press to create text file", command = clicked)
entry1.pack()
button1.pack()
root.mainloop()
This will make a function that runs when the button is clicked, it will get the text in the entry box then make a file path, finally it will attempt to open this file, as the file doesn't exist it will instead create a new file under this name.
Simple example
import tkinter as tk
def write_file():
name = e.get() # get text from entry
with open(name + ".txt", "w") as f: # open file
f.write("Hello World\n") # write doesn't add '\n'
# `with` will close file automatically
root = tk.Tk()
e = tk.Entry(root)
e.pack() # can't be `e = Widget(...).pack()`
tk.Button(root, text="Save", command=write_file).pack()
root.mainloop()

Playing mp3 files using python 2.7 buttons - TKinter

Hello I am trying to create a button that plays a mp3 file using TKinter so far I have the following code. I cant get it to play the mp3 file
from Tkinter import *
import os
import winsound
app = Frame(root)
app.pack(side='bottom')
button1 = Button(app, text="Enter Program", command=winsound.PlaySound('music.mp3',winsound.SND_FILENAME))
button1.pack()
Thanks
You can use pyglet library to play mp3 files but you should also have installed avbin library. (https://code.google.com/p/avbin/)
Another problem is, tkinter has its own main loop and pyglet has its own. So you should use threads. This code might give you an idea:
from Tkinter import *
from threading import Thread
import pyglet
root = Tk()
app = Frame(root)
app.pack(side='bottom')
player = pyglet.media.Player()
music_file = pyglet.media.load('foo.mp3')
def startPlaying():
player.queue(music_file)
player.play()
pyglet.app.run()
def playSound():
global sound_thread
sound_thread = Thread(target=startPlaying)
sound_thread.start()
button1 = Button(app, text="Enter Program", command=playSound)
button1.pack()
root.mainloop()
pyglet.app.exit()
You have two mistakes there:
The classic command error: When you pass an argument like this:
Button(..., command=winsound.PlaySound(...))
you're calling PlaySound and use its return value (which defaults to None), so you're passing command=None. Use lambda:
Button(..., command=lambda: winsound.PlaySound(...))
winsound is not made to play mp3s, but wavs. Use another library, suggestions can be found here.

python 2.7 while loop, ttk.progressbar not working

I am working on a progress bar that keeps track of a certain function in pygame.
The following code causes a loop that I must force quit. And I can not figure our my error. Any help would be great.
from Tkinter import *
import ttk
import sys
import pygame
myGui = Tk()
myGui.title("Progress Bar")
myGui.geometry("400x200+200+300")
value_progress = StringVar()
pygame.mixer.init()
pygame.mixer.music.load("/home/david/Documents/aaa.mp3")
pygame.mixer.music.play()
def position():
global value_progress
while pygame.mixer.music.get_busy() == True:
value_progress.set(float(pygame.mixer.music.get_pos()))
b = Button(myGui, text="Start", )
b.pack()
p = ttk.Progressbar(myGui, variable=value_progress,
mode='determinate', length=350,
maximum= 512920)
p.pack()
I call the function from the shell. and then it stalls and does not come out of it.
This is only the progress bar portion of my work. However, it causes the program to crash every time.
Do not loop. Instead try following code:
def position():
global value_progress
if pygame.mixer.music.get_busy():
value_progress.set(float(pygame.mixer.music.get_pos()))
myGui.after(100, position)
Tk.after(ms, f) call f after specified ms millisecond.

Visual Studio Console Window Location

Is it possible to make the console window in Visual Studio show up in the same location on screen for each compile?
I always have to move it around whenever I compile because its starting location overlaps things.
By default you can change console window settings per application and windows will save them for the next time when this application is run. You may change the start location by clicking right button on the console title bar, then choosing Properties and Layout tab. Then uncheck the "Let system position window" checkbox and type the coordinates you would like.
Unfortunately Visual Studio when you run an application without the debugger (Ctrl + F5) will launch the cmd.exe /c <your app> command. So changing properties on this window will also change settings for all console sessions in the system.
This does not apply to the debug run as under the debugger VS launches just the application and so the settings apply only to its console windows.
I came here with the same problem, and was sure there must be an option in VS. I ended up writing a quick python script that runs in the background, searches for the window and sets its last position. Also optionally sets it to always on top, and persists the position in a file. Hopefully will help someone else out.
import win32api
import win32gui
import win32con
import msvcrt
import sys
import time
import threading
import pywintypes
import argparse
import re
import weakref
import pickle
def log_message(message,*args):
print(("[%s]" % message).ljust(30) ," ... ",*(str(arg) for arg in args))
def make_file_name(arguments):
return arguments.save_file_name or "window_" + re.sub("[^a-z]","_",arguments.title_text,flags=re.IGNORECASE)
def update_proc(flags,arguments):
found_pos = (0,0,500,500)
found_hwnd = -1
if arguments.save_to_file and not arguments.reset:
load_file_name = make_file_name(arguments)
try:
with open(load_file_name,"rb") as load_file:
found_pos = pickle.load(load_file)
except:pass
while not flags.exit:
try:
hwnd = win32gui.FindWindow(arguments.class_text,arguments.title_text)
if not hwnd: continue
if hwnd != found_hwnd:
log_message("new window found",hwnd)
for _ in range(10):
win32gui.SetWindowPos(hwnd,0 if not arguments.on_top else win32con.HWND_TOPMOST,*found_pos,0)
time.sleep(0.01)
log_message("setting window position",found_pos)
found_hwnd = hwnd
time.sleep(0.1)
if win32gui.IsIconic(found_hwnd):
continue
rect = win32gui.GetWindowRect(found_hwnd)
new_pos = (rect[0],rect[1],rect[2]-rect[0],rect[3]-rect[1])
#ignore negative pos
if True in [ r < 0 for r in new_pos[0:2] ]:
continue
if new_pos == found_pos:
continue
if arguments.save_to_file:
log_message("saving position",new_pos)
save_file_name = make_file_name(arguments)
try:
with open(save_file_name,"wb") as save_file:
pickle.dump(new_pos,save_file)
except:pass
else:
log_message("updading stored position",new_pos)
found_pos = new_pos
except pywintypes.error:pass
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-s","--savetofile",help="Save window settings to a file",action="store_true",dest="save_to_file")
parser.add_argument("-sfn","--savefilename",type=str,help="File name to use if --savetofile specified (or a default is generated)",dest="save_file_name")
parser.add_argument("-ot","--ontop",help="Window Always Ontop",dest="on_top",action="store_true")
parser.add_argument("-c","--class",type=str,help="Window Class Name",dest="class_text")
parser.add_argument("-r","--reset",help="Reset Window Position",action="store_true")
parser.add_argument("-t","--title",type=str,help="Window Title Text",required=True,dest="title_text")
arguments = parser.parse_args()
flags = type("", (), {"exit":False})()
update_thread = threading.Thread(target=update_proc,args=[weakref.proxy(flags),arguments])
update_thread.start()
if arguments.save_to_file:
log_message("saving to file",make_file_name(arguments))
while True:
if flags.exit: break
key = msvcrt.getch()
if key == b'q':
flags.exit = True
log_message("exiting")
break
update_thread.join()