Python NameError: глобальное имя 'разрешение' не определяется

Я работаю над разработкой приложения Python для Ubuntu, которая позволяет пользователю иметь их нужное разрешение, не требуя графических драйверов.
Чтобы сделать это, я использовал xrandr.
Однако я теперь встретился с проблемой, несмотря на поиск других с подобными проблемами и попыткой мер.

Вот мой код (я плохо знаком с Python, при этом этот мое первое приложение, таким образом, код, вероятно, будет очень грязен и неэффективен другим - я также должен переместить часть кода, но надо надеяться это читаемо):

#!/usr/bin/python

import gtk, sys
import os, commands     # enables us to use xrandr

class ResolutionX(gtk.Window):

    # create an instance of ResolutionX
    def __init__(self):
        # constructor
        super(ResolutionX, self).__init__()

        # set the default window values
        self.set_title("ResolutionX")
        self.set_size_request(600, 200)
        self.set_position(gtk.WIN_POS_CENTER)

        fix = gtk.Fixed()

        # resolution combo box
        ResComboB = gtk.combo_box_new_text()
        ResComboB.append_text('1024 x 768')
        ResComboB.append_text('1280 x 960')
        ResComboB.append_text('1366 x 768')
        ResComboB.append_text('1280 x 1024')
        ResComboB.append_text('1440 x 900')
        ResComboB.append_text('1440 x 960')
        ResComboB.append_text('1440 x 1080')
        ResComboB.append_text('1600 x 1200')
        ResComboB.append_text('1920 x 1080')
        ResComboB.append_text('1920 x 1200')
        ResComboB.set_active(0)
        ResComboB.connect("changed", ResComboB_changed)

        label = gtk.Label("Resolution:")

        # apply button
        applyBtn = gtk.Button("Apply")
        applyBtn.set_size_request(110, 29)
        applyBtn.connect("clicked", applyBtn_on_clicked)

        # add widgets to the main window
        fix.put(ResComboB, 98, 78)
        fix.put(label, 30, 85)
        fix.put(applyBtn, 470, 78)
        self.add(fix)

        self.connect("destroy", gtk.main_quit)
        self.show_all()


def ResComboB_changed(ResComboB):
    string = ResComboB.get_active_text()
    stringRes = string.replace("x", "")
    echo = "echo "
    stringConfig = os.popen("cvt " + stringRes).readlines()

    # TODO: create a hidden directory in /home folder

    # create the file [config.sh]
    fWrite = open('config.sh', 'w')
    # write the xrandr configuration into the file so we can edit it
    print >> fWrite, stringConfig
    fWrite.close()

    fRead = open('config.sh', 'r')

    # TODO: remove last 4 characters from readString // DONE

    # get input from [config.sh] and edit  according to the choice of resolution
    if (string=="1024 x 768"):
        for line in fRead:
            storedString = line
            readString = storedString[83:]
            readString = readString[:76]
            print readString # verification
            resolution = readString[:16]
    if (string=="1366 x 768"):
        for line in fRead:
            storedString = line
            readString = storedString[76:]
            readString = readString[:76]
            print readString # verification
            resolution = readString[:16]
    if (string=="1280 x 960") or (string=="1440 x 900"):
        for line in fRead:
            storedString = line
            readString = storedString[84:]
            readString = readString[:77]
            print readString # verification
            resolution = readString[:16]
    if (string=="1440 x 960"):
        for line in fRead:
            storedString = line
            readString = storedString[77:]
            readString = readString[:76]
            print readString # verification
            resolution = readString[:16]
    if (string=="1280 x 1024") or (string=="1440 x 1080") or (string=="1600 x 1200") or (string=="1920 x 1080") or (string=="1920 x 1200"):
        for line in fRead:
            storedString = line
            readString = storedString[85:]
            readString = readString[:81]
            print readString # verification
            resolution = readString[:17]
    os.system("xrandr --newmode " + readString)

    fRead.close()

def applyBtn_on_clicked(applyBtn):

    # detect and store monitor output type - eg. VGA1, DVI-0
    monitorType = os.popen("xrandr | grep ' connected ' | awk '{ print$1 }'").readlines()
    fWrite = open('config.sh', 'w')
    print >> fWrite, monitorType
    fWrite.close()
    # get the input from [config.sh]
    fRead = open('config.sh', 'r')
    for line in fRead:
        CmonitorType = line
    fRead.close()
    # edit CmonitorType so we can use it
    CmonitorType = CmonitorType[2:]
    CmonitorType = CmonitorType[:7]
    print CmonitorType # verification

    os.system("xrandr --addmode " + CmonitorType + resolution)

ResolutionX()
gtk.main()

Я получаю эту ошибку:
Traceback (most recent call last): File "file.py", line 129, in applyBtn_on_clicked os.system("xrandr --addmode " + CmonitorType + resolution) NameError: global name 'resolution' is not defined

Как я могу решить эту проблему?

1
задан 26 April 2016 в 10:36

1 ответ

Внесите следующие изменения в свой сценарий:

Ниже строки def ResComboB_changed(ResComboB): добавляют следующее к нему, таким образом, это похоже на это:

def ResComboB_changed(ResComboB):
    global resolution

или добавляют resolution = "" выше строки определения как это:

resolution = ""
def ResComboB_changed(ResComboB):

Hope, которая помогает ;)

2
ответ дан 7 December 2019 в 13:56

Другие вопросы по тегам:

Похожие вопросы: